<?php

namespace App\Http\Services;

use App\Http\Model\ContentCheck;
use App\Http\Model\Family;
use App\Http\Model\FinanceDiamond;
use App\Http\Model\FinanceRoomWealth;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\Gift;
use App\Http\Model\GroupChat;
use App\Http\Model\Hint;
use App\Http\Model\Mall;
use App\Http\Model\Medal;
use App\Http\Model\Room;
use App\Http\Model\RoomScore;
use App\Http\Model\RoomUser;
use App\Http\Model\SystemConfig;
use App\Http\Model\Union;
use App\Http\Model\UnionRank;
use App\Http\Model\UnionParam;
use App\Http\Model\UnionUser;
use App\Http\Model\User;
use App\Http\Model\UserProp;
use App\Http\Model\UserVerify;
use App\Lib\oss;
use App\Lib\rc;
use App\Http\Model\FinanceRoomWallet;
use Illuminate\Support\Facades\DB;
use App\Lib\SendSms;
use App\Http\Model\Settle;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\UserAgent;
use App\Http\Services\NewRoomServices;

class UnionServices extends CommonServices
{

    private $model_room_user;
    private $model_room;
    private $lib_rong;
    private $model_union;
    private $model_user_union;//公会用户model
    protected $user;
    private $model_finance_room_wallet;
    private $FinanceRoomWealth;
    protected $userWallet;
    protected $model_group;
    protected $model_user_verify;
    protected $model_gift;
    protected $model_union_rank;
    protected $modelMedal;
    protected $model_mall;
    protected $userPropModel;
    protected $financeDiamond;
    protected $model_content_check;
    protected $model_union_param;
    protected $model_family;
    protected $service_room_msg;
    protected $service_msg;//系统消息推送
    protected $smsService;//短信发送通知
    protected $union_user_set_rate_key = "UNION:SETUSERRATE:"; //string UNION:SETUSERRATE: => 1 公会长设置公会成员费率缓存1周 
    protected $smsPrefix = 'sms_union_rate';//对公成员获取验证码

    protected $settleModel;
    protected $systemServices;
    protected $userAgentModel;
    protected $redis_get_user_list_Union = 'UNION:USER:LIST:bill:'; //公会房间日流水
    protected $defaultConst = [
        'member_total_count_limit' => 1000,// 群组成员总数限制
        'member_admin_count_limit' => 20,// 群组管理员总数限制
    ];

    //对私主播分成
    protected $baseRate = 68;//对私主播默认比例
    protected $maxRate = 70;//对私主播分成可设置最大值
    protected $minRate = 60;//对私主播分成可设置最小值
    protected $rateStep = 1;//每次调整步长

    public function __construct()
    {
        $this->model_room_user = new RoomUser();
        $this->model_room = new Room();
        $this->lib_rong = new rc();
        $this->user = new User();
        $this->userWallet = new FinanceUserWallet();
        $this->model_union = new Union();
        $this->model_user_union = new UnionUser();
        $this->model_group = new GroupChat();
        $this->model_user_verify = new UserVerify();
        $this->model_finance_room_wallet = new FinanceRoomWallet();
        $this->FinanceRoomWealth = new FinanceRoomWealth();
        $this->model_gift = new Gift();

        $this->model_mall = new Mall();
        $this->userPropModel = new UserProp();
        $this->modelMedal = new Medal();
        $this->financeDiamond = new FinanceDiamond();
        $this->model_union_rank = new UnionRank();
        $this->model_content_check = new ContentCheck();
        $this->model_union_param = new UnionParam();
        $this->model_family = new Family();
        $this->service_room_msg = new RoomMsgServices();
        $this->settleModel = new Settle();
        $this->service_msg = new MsgServices(); //系统推送通知服务
        $this->smsService = new SendSms(); //短信发送服务
        $this->systemServices = new SystemServices();
        $this->userAgentModel = new UserAgent();

    }

    //创建公会
    public function createUnion($user_id, $name, $portrait, $sort, $notice, $desc, $settleType, $unionCompany, $unionBankName, $unionBankNo, $rewardType = 0)
    {
        $data['un_user_id'] = $user_id;
        $union_info = $this->model_union->getUnionInfoToUnUserId($user_id);
        if ($union_info) {
            return false;
        }
        $data['name'] = $name;
        $data['portrait'] = $portrait;
        $data['sort'] = $sort;
        $data['notice'] = $notice;
        $data['desc'] = $desc;
        $data['settle_type'] = ($settleType == 2) ? 2 : 1;
        $data['union_company'] = $unionCompany;
        $data['union_bank_name'] = $unionBankName;
        $data['union_bank_no'] = $unionBankNo;
        $data['reward_type'] = $rewardType;
        $creted_union_id = $this->model_union->createUnion($data);
        if (!$creted_union_id) {
            return false;
        }
        $union_data['un_id'] = $creted_union_id;
        $union_data['user_id'] = $user_id;
        $union_data['role_id'] = 1; // 会长权限id
        $this->model_user_union->createUnionUser($union_data);
        $this->model_union_rank->setContribution($creted_union_id);

        $this->checkUserSetAgent($creted_union_id);

        return $creted_union_id;
    }

    public function updateUnion($data)
    {
        $id = $data['id'];
        unset($data['id']);
        unset($data['_url']);
        $res = $this->model_union->updateUnion($id, $data);
        if ($res) {
            if (isset($data['authentication_status'])) {
                //公会成员
                $users = $this->model_user_union->getUserNum($id, false);
                $user_ids = array_column($users, 'user_id');

                if ($data['authentication_status'] == 0) {
                    //删除用户代理
                    $this->userAgentModel->agentUserDelList($user_ids);
                }
                if ($data['authentication_status'] > 0) {
                    //判断用户是否是主播是主播的话设置为代理
                    foreach ($user_ids as $userId) {
                        $this->checkUserSetAgent($userId);
                    }
                }
            }
        }

        return $res;
    }

    /**
     * CBD公会房间创建
     * $businessType  1cbd  0小屋
     * */
    public function createRoomByCBD($union_id, $businessType = 1, $adminName)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $union_info = $this->model_union->getUnionInfo($union_id);
            if (!$union_info) {
                $code = Hint::ERR_FAIL;
                $msg = '公会信息错误';
                break;
            }
            // 取出房间ID池中已生成的房间UID
            $roomUid = $this->model_room->generatedRoomUid();
            if (empty($roomUid)) {
                $code = Hint::ERR_FAIL;
                $msg = '房间ID池已空，请先灌满房间ID池后再次生成';
                break;
            }

            // 查询用户信息
            $userData = $this->user->get_user($union_info['un_user_id']);
            $image = $userData['images'][0] ?? '';
            if (!empty($image)) {
                $image = parse_url($image)['path'] ?? '';
            }

            DB::beginTransaction();

            // 创建房间数据 默认为认证
            $roomId = $this->model_room->create_room([
                'user_id' => $union_info['un_user_id'],
                'room_uid' => $roomUid,
                'image' => $image,
                'business_type' => $businessType,
                'certified' => 1,
            ]);
            if ($roomId <= 0) {
                $code = Hint::ERR_DATA_CREATE_FAIL;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            // 添加房间默认管理员
            $this->model_room->add_role($roomId, $union_info['un_user_id'], 2);
            // 初始化房间财富值
            $this->model_finance_room_wallet->add_wallet($roomId);
            // 添加收藏
            $this->model_room->add_collect($roomId, $union_info['un_user_id']);
            //添加公会房间关联
            $addRoomData['room_id'] = $roomId;
            $addRoomData['user_id'] = $union_info['un_user_id'];
            $addRoomData['un_id'] = $union_id;
            $this->model_union->joinUnionRoom($addRoomData);
            DB::commit();
            $data['room_id'] = intval($roomId);
            $data['room_uid'] = intval($roomUid);
            $this->model_room->addRoomAdmin($roomId, $adminName);
        } while (false);
        return compact('code', 'msg', 'data');
    }


    //p
    public function joinRoomByCBD($union_id, $room_id)
    {
        //添加公会房间关联
        $addRoomData['room_id'] = $room_id;
        $union_info = $this->model_union->getUnionInfo($union_id);
        if (!$union_info) {
            return false;
        }
        $addRoomData['user_id'] = $union_info['un_user_id'];
        $addRoomData['un_id'] = $union_id;
        return $this->model_union->joinUnionRoom($addRoomData);
    }

    //公会列表
    public function getList($input)
    {
        if (!empty($input['search'])) {
            $res = $this->model_union->getUnionList($input);
        } else {
            $is_new = $input['is_new'] ?? 0;
            $page = $input['page'] ?? 0;
            $pageSize = $input['pageSize'] ?? 5;
            $unions = $this->model_union_rank->getContributionRank($is_new, $page, $pageSize);
            if (empty($is_new)) {
                $res = empty($unions) ? [] : $this->model_union->getUnions($unions);
            } else {
                if (!empty($unions)) {
                    $res = array_slice($unions, $page * $pageSize, $pageSize);
                } else {
                    $res = [];
                }
            }
        }
        foreach ($res as &$v) {
            $union_id = $v['id'];
            $v['level'] = $this->model_union_rank->getWealthLevel($union_id);
            $v['finance_total'] = $this->model_union_rank->getWealth($union_id);
            $v['active_total'] = $this->model_union_rank->getActiveWealth($union_id);
            $v['adapt_portrait'] = $this->model_union->buildUnionImage($v['portrait']);
            $v['portrait'] = build_image($v['portrait']);
        }
        return $res;
    }

    //申请公会
    public function applyUnion($user_id, $union_id)
    {
        //获取用户公会
        $user_union = $this->model_user_union->userToUnion($user_id, 3);
        //查看用户申请记录
        $apply_log = $this->model_union->applyUserLog($user_id, $union_id);
        //获取公会信息
        $union_info = $this->model_union->getUnionInfo($union_id);
        $code = Hint::ERR_FAIL;
        $msg = '加入失败';
        $data = [];
//        $check_time = $this->model_union->checkUserDelTime($user_id);
        do {
            if (!$union_info) {
                $code = Hint::ERR_FAIL;
                $msg = '公会不存在';
                break;
            }
//            if ($check_time) {
//                $code = Hint::ERR_FAIL;
//                $msg = '距上次离开公会时间低于120小时';
//                break;
//            }
            if ($user_union) {
                $code = Hint::ERR_FAIL;
                $msg = '您当前已有公会，需要退出当前公会，才能再次申请';
                break;
            }
            if ($apply_log && $apply_log[0]['created_at'] > date('Y-m-d H:i:s', strtotime('-1 days'))) {
                $code = Hint::SAME_TIME_NOT_REPEAT;
                $msg = '申请成功，请耐心等待通过';
                $data['union_id'] = $union_info['id'];
                $data['apply_user_id'] = $user_id;
                break;
            }
            //判断是否实名验证
            $user_verify = $this->model_user_verify->getSuccess($user_id);
            if (empty($user_verify)) {
                $code = Hint::USER_NOT_CERTIFICATION;
                break;
            }
            //同一实名身份证不可加入多个公会
            $user_verify_users = $this->model_user_verify->getAllIcCard($user_verify['idcard_number']);
            $user_ids = array_column($user_verify_users, 'user_id');
            $userUnionList = $this->model_union->getUserUnion($user_ids);
            if (!empty($userUnionList)) {
                $unionIds = array_unique(array_column($userUnionList, 'un_id'));
                if (count($unionIds) > 1 || !in_array($union_id, $unionIds)) {
                    $code = Hint::UNION_USER_EXIST;
                    $msg = '同一实名身份证不可加入多个公会';
                    break;
                }
            }

            //申请入公会
            $apply_union = $this->model_union->applyUnionToUser($user_id, $union_id);
            if ($apply_union) {
                $code = Hint::SUCCESS;
                $msg = '申请成功';
                $data['union_id'] = $union_info['id'];
                $data['apply_user_id'] = $user_id;
                break;
            }
        } while (false);
        return compact('code', 'msg', 'data');
    }

    //申请公会列表
    public function applyUnionlist($user_id, $union_id)
    {
        //获取用户公会
        $user_union = $this->model_user_union->userToUnion($user_id, 3);
        //查看用户申请记录
        $apply_log = $this->model_union->getInviteUnionLog($union_id);
//        $coutapply = $this->model_union->countInviteUnionLog($union_id);
        //获取公会信息
        $union_info = $this->model_union->getUnionInfo($union_id);
//        $check_room_role_type = $this->model_union->get_role($user_id);
        $data = [];
        do {
            if (!$union_info) {
                $code = Hint::ERR_FAIL;
                $msg = '公会不存在';
                break;
            }
//            if ($check_room_role_type!=2) {
//                $code = Hint::ERR_FAIL;
//                $msg = '无权操作';
//                break;
//            }
            foreach ($apply_log as $k => $v) {
                $assign_user_info = $this->user->get_user($v['user_id']);
                $check_role_type = $this->model_union->get_role($v['user_id']);
                $data[$k]['union_id'] = $union_id;
                $data[$k]['union_name'] = $union_info['name'];
                $data[$k]['user_name'] = $assign_user_info['nickname'];
                $data[$k]['user_uid'] = $assign_user_info['user_uid'];
                $data[$k]['role_type'] = $check_role_type;
                $data[$k]['user_id'] = $assign_user_info['user_id'];
                $data[$k]['status'] = $v['status'];
                $data[$k]['timestemp'] = $v['created_at'];
                $data[$k]['image'] = build_image($assign_user_info['images'][0] ?? '');

            }
            $data = array_values($data);
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;


        } while (false);
        return compact('code', 'msg', 'data');
    }

//申请公会列表
    public function applyCountUnionlist($user_id, $union_id)
    {
        //获取用户公会
        $user_union = $this->model_user_union->userToUnion($user_id, 3);
        //查看用户申请记录
        $coutapply = $this->model_union->countInviteUnionLog($union_id);
        //获取公会信息
        $union_info = $this->model_union->getUnionInfo($union_id);
        $data = [];
        do {
            if (!$union_info) {
                $code = Hint::ERR_FAIL;
                $msg = '公会不存在';
                break;
            }
            $data['count'] = $coutapply;
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;


        } while (false);
        return compact('code', 'msg', 'data');
    }

    //获取满足审批权限用户
    public function getAuditUnionUserIds($union_id)
    {
        //查询公会管理层
        $ids = [];
        $union_role = $this->model_user_union->getUnionUserList($union_id, '');
        if (!$union_role) {
            return $ids;
        }
        foreach ($union_role['role_user'] as $v) {
            $check_role = $this->model_user_union->checkUserRole($v['user_id'], 1, $union_id);
            if ($check_role > 0) {
                $ids[] = $v['user_id'];
            }
        }
        return $ids;
    }

    //获取用户公会
    public function getUserUnion($user_id, $union_id = 0, $phone = '')
    {
        $code = Hint::ERR_FAIL;
        $msg = '失败';
        $data = [];
        //查询用户公会信息
        $data['union_status'] = 0; //他人公会
        $data['look_user_id'] = $user_id;
        $user_info = $this->model_user_union->userToUnion($user_id, 3);
        $data['user_rule'] = $user_info['u_rule'];
        $user_un_id = $user_info['union_id'] ?? 0;
        $data['group_info'] = null;
        $data = [];

        if ($user_un_id == $union_id) {
            //本人公会
            $data['look_user_id'] = $user_id;
            $user_info['name'] = $user_info['union_name'];
            $union_info = $user_info;
            $data['union_status'] = 1;
            $data['role_id'] = $union_info['role_id'];
//            $data['role_type'] = $check_room_role_type;
            // $group_id = $this->model_group->getGroupChatByUnion($user_un_id);
            // $data['group_info'] = $this->model_group->getGroupChatByIdArray([$group_id])[0];
            //

            //今日签到数据
            $today_sign = $this->model_union_rank->getTodayTotalSignData($union_id);
            $data['today_sign_num'] = count($today_sign);
            $sign_portrait = [];
            for ($i = 0; $i < 3; $i++) {
                if (!empty($today_sign[$i])) {
                    $sign_portrait[] = $this->user->get_user($today_sign[$i])['images'][0];
                }
            }
            $data['today_sign_portrait'] = $sign_portrait;
            //今日捐赠数据
            $today_donation = $this->model_union_rank->getTodayTotalDonation($union_id);
            $data['today_donation_num'] = count($today_donation);
            $donation_portrait = [];
            for ($i = 0; $i < 3; $i++) {
                if (!empty($today_donation[$i])) {
                    $donation_portrait[] = $this->user->get_user($today_donation[$i])['images'][0];
                }
            }
            $data['today_donation_portrait'] = $donation_portrait;
            $data['is_sign'] = $this->model_union_rank->getTodaySignData($union_id, $user_id);
            $data['is_donation'] = $this->model_union_rank->getTodayDonation($union_id, $user_id);

            //是否显示【公开房管理】入口
            if ($union_info['role_id'] == 1) { //会长(房主)必然显示
                $data['cbd_manage_entrance'] = 1;
            } else {
                //读取公会房间中，我是超管的房间
                $union_rooms = $this->model_union->getUnionRoomIds($union_id);
                if (empty($union_rooms)) {
                    $data['cbd_manage_entrance'] = 0;
                } else {
                    $union_room_ids = array_column($union_rooms, 'room_id');
                    $roles = $this->model_room->get_roles_by_room_ids($user_id, 2, $union_room_ids);
                    $data['cbd_manage_entrance'] = count($roles) > 0 ? 1 : 0;
                }
            }

        } else {
            //查看公会
            $union_info = $this->model_union->getUnionInfo($union_id);
            $data['role_id'] = -1;//他人公会
            if ($user_info['union_id'] == $union_id) {
                $data['union_status'] = 1;// 本人公会
                $data['role_id'] = $user_info['role_id'];
            }
//            $data['union_status'] = 1;// 本人公会
//            $data['role_id'] = empty($user_info['role_id'])?"-1":$user_info['role_id'];
            $yesterday_sign = $this->model_union_rank->getYesterdayTotalSignData($union_id);
            $data['yesterday_sign_num'] = count($yesterday_sign);
            $yesterday_donation = $this->model_union_rank->getYesterdayTotalDonationData($union_id);
            $data['yesterday_donation_num'] = count($yesterday_donation);
        }
        do {
            if (!$union_info) {
                $code = Hint::ERR_FAIL;
                $msg = '公会不存在';
                break;
            }
            if ($union_info['un_user_id'] == $user_id) {
                $union_info['un_user_phone'] = substr_replace($phone, '****', 3, 4);
                $union_info['un_dissolve_code'] = $this->model_union->getDissolveCode($union_id);
            }
            $data['rule_status'] = $union_info['rule'];

            //获取公会房间
            $data['room_list'] = $this->getUnionRoomList($union_id);
            $data['union_info'] = $union_info;
//           var_dump($union_info);
            $data['union_info']['portrait'] = build_image($data['union_info']['portrait']);
            $total = $this->model_union_rank->getWealth($union_id);
            $data['speed'] = 1;
            $data['total'] = $total;
            if ($total > 80000000) {
                $data['speed'] = 100;
                $data['level'] = 15;
                $data['total'] = 80000000;
                $data['end_value'] = 80000000;
            } else {
                $union_rank = $this->model_union->getUnionRank($total);
                $data['level'] = $union_rank[0]['level'];
                $data['end_value'] = $union_rank[0]['end_value'];
                $real_value = $union_rank[0]['end_value'] - $union_rank[0]['start_value']; // 晋级值
                $real_total = $total - $union_rank[0]['start_value'];
                $data['speed'] = round($real_total / $real_value * 100, 2);
            }
//            foreach ($data['room_list'] as $k=>$v2){
//                $check_room_role_type = $this->model_union->get_roleV2($user_id,$v2['room_id']);
//                if($check_room_role_type['role_type']==2){
//                    $data['union_info']['role_type']=empty($check_room_role_type['role_type']) ? 0 : 2; //检查超管
//                }else{
//                    $data['union_info']['role_type']=0;
//                }
//            }
            if ($union_info['role_id'] == 0) {
                $data['union_info']['role_type'] = 0;
            } else {
                $data['union_info']['role_type'] = 2;
            }
            $data['active_total'] = $this->model_union_rank->getActiveWealth($union_id);
            $data['authentication_status'] = $union_info['authentication_status'];
            //获取公会成员
            $code = Hint::SUCCESS;
            $msg = '成功';
            $user_list = $this->model_user_union->getUnionUserList($union_id, '');
            $userCount = count($user_list['role_user']) + count($user_list['user']);
            $data['count_user'] = $userCount > 500 ? '500+' : $userCount;
            $data['user_list'] = array_slice(array_merge($user_list['role_user'], $user_list['user']), 0, 4);
        } while (false);
        return compact('code', 'msg', 'data');
    }

    //查看工会总流水
    public function showUnionFinanceALL($union_id)
    {
        $unionAll = $this->model_union->getUnionFinanceALL($union_id);
        return $unionAll;
    }

    //查看工会总流水
    public function showUnionFinanceALLHistory($union_id)
    {
        $unionAll = $this->model_union->getUnionFinanceALLHistory($union_id);
        return $unionAll;
    }

    //获取公会信息
    public function getUnionInfo($union_id)
    {
        //获取公会房间
        $union_data = $this->model_union->getUnionInfo($union_id);
        $union_data['level'] = $this->model_union_rank->getWealthLevel($union_id);
        $union_data['portrait'] = build_image($union_data['portrait']);
        return $union_data;
    }

    //获取公会信息
    public function getUserUnionInfo($user_id)
    {
        $union_info = $this->model_user_union->userToUnion($user_id, 3);
        if (isset($union_info['union_id'])) {
            $union_info['active_total'] = $this->model_union_rank->getActiveWealth($union_info['union_id']);
            $union_info['finance_total'] = $this->model_union_rank->getWealth($union_info['union_id']);
        }
        return $union_info;
    }

    //获取公会信息
    public function getUserMyUnion($request)
    {
        $user_info = $this->user->get_current_user();
        $user_id = !empty($request['other_user_id']) ? $request['other_user_id'] : $user_info['user_id'];
        $data['user_id'] = $user_id;
        $user_info = $this->user->get_user($user_id);
        $data['active_certify'] = $user_info['active_certify'];
        $union_info = $this->model_user_union->userToUnion($user_id, 3);
        if (isset($union_info['union_id'])) {
            $union_info['active_total'] = $this->model_union_rank->getActiveWealth($union_info['union_id']);
            $union_info['finance_total'] = $this->model_union_rank->getWealth($union_info['union_id']);
        }
        $data['union_info'] = $union_info;
        return $data;
    }

    //获取公会房间列表
    public function getUnionRoomList($union_id)
    {
        $union_rooms_ids = $this->model_union->getUnionRoomIds($union_id);
        $room_ids = [];
        if ($union_rooms_ids) {
            $room_ids = array_column($union_rooms_ids, 'room_id');
        }
        $union_room_list = $this->model_room->get_rooms_by_ids($room_ids);
//        $union_room_list_rank = $this->model_room->getRoomListRank($room_ids);
        // 获取用户当前所在房间
//            $currUserRoomId = $this->roomUserModel->get_user_cur_room($this->requestData['user_id']);

        $un_room_open = [];
        $un_room_close = [];
        foreach ($union_room_list as $key => $value) {
            //房间是否开启
            $opened = $this->model_room->get_opened($value['room_id']);
            if ($opened) {
                $value['opened'] = true;
                $un_room_open[] = $value;
            } else {
                $value['opened'] = false;
                $un_room_close[] = $value;
            }
        }

        if ($un_room_open) {
            return array_merge($un_room_open, $un_room_close);
        }
        return $un_room_close;
    }

    //获取公会成员
    public function getUnionUserList($user_id, $search = '', $union_id = 0)
    {
        //获取公会成员
        $union_info = $this->model_user_union->userToUnion($user_id, 1);
        $union_user_list = $this->model_user_union->getUnionUserList($union_info['un_id'], $search);

        if (!empty($union_id)) {
//            $key = $this->redis_get_user_list_Union . $union_id;
//            $resuser= Redis::get($key);
//            if(empty($resuser)) {
            foreach ($union_user_list['user'] as &$u) {
//                    $u['sign_num'] = $this->model_union_rank->getContinueSignDays($union_id, $u['user_id']);
                //获取公会成员费率配置
//                    $union_user_rate = $this->model_user_union->getUnionUserRate($union_id, $u['user_id'], true);
                $configMap = [];
                $config = $this->systemServices->get_config();
                foreach ($config as $k => $v) {
                    $value = $v['value'];
                    if ($v['type'] == 1) {
                        $value = intval($v['value']);
                    }
                    $configMap[$k] = $value;
                }
                $kk_to_diamond = $configMap['charm_to_kk'];
                $u['user_rate'] = empty($kk_to_diamond) ? "0" : $kk_to_diamond;
                $unionUserAll = $this->model_union->getUnionUserFinanceALL($u['user_id']);
                $u['user_consumer'] = $unionUserAll['total'] ?? "0";
            }
//                if(!empty($union_user_list['user'])) {
//                    Redis::setex($key, 3600, json_encode($union_user_list['user']));
//                }
//            }else{
//                $union_user_list['user']=json_decode($resuser,true);
//            }
            foreach ($union_user_list['role_user'] as &$r_u) {
                $unionUserAll = $this->model_union->getUnionUserFinanceALL($r_u['user_id']);
                $r_u['user_consumer'] = $unionUserAll['total'] ?? "0";
                $r_u['sign_num'] = $this->model_union_rank->getContinueSignDays($union_id, $r_u['user_id']);
            }
        }

        $res['user'] = $union_user_list['user'];
//        $res['role_user'] = $union_user_list['role_user'];
        return $res;
    }

    public function getUnionUserListV2($user_id, $search = '', $union_id = 0, $page, $page_size)
    {
        //获取公会成员
        $union_info = $this->model_user_union->userToUnion($user_id, 1);
        $union_user_list = $this->model_user_union->getUnionUserListV2($union_info['un_id'], $search, $page, $page_size);

        if (!empty($union_id)) {
            foreach ($union_user_list['user'] as &$u) {
//                    $u['sign_num'] = $this->model_union_rank->getContinueSignDays($union_id, $u['user_id']);
                //获取公会成员费率配置
//                    $union_user_rate = $this->model_user_union->getUnionUserRate($union_id, $u['user_id'], true);
                $configMap = [];
                $config = $this->systemServices->get_config();
                foreach ($config as $k => $v) {
                    $value = $v['value'];
                    if ($v['type'] == 1) {
                        $value = intval($v['value']);
                    }
                    $configMap[$k] = $value;
                }
                $kk_to_diamond = $configMap['charm_to_kk'];
                $u['user_rate'] = empty($kk_to_diamond) ? "0" : $kk_to_diamond;
                // $unionUserAll = $this->model_union->getUnionUserFinanceALL($u['user_id']);
                // $u['user_consumer'] = $unionUserAll['total'] ?? "0";
                $u['user_consumer'] = "";
            }
            foreach ($union_user_list['role_user'] as &$r_u) {
                // $unionUserAll= $this->model_union->getUnionUserFinanceALL($r_u['user_id']);
                // $r_u['user_consumer']=$unionUserAll['total']??"0";
                $r_u['user_consumer'] = "";
                $r_u['sign_num'] = $this->model_union_rank->getContinueSignDays($union_id, $r_u['user_id']);
            }
        }
//        if($page==0){
//            $res['role_user'] = empty($union_user_list['role_user'])?[]:$union_user_list['role_user'];
//        }
        $res['role_user'] = empty($union_user_list['role_user']) ? [] : $union_user_list['role_user'];
        $res['user'] = $union_user_list['user'];

        return $res;
    }

    /**
     * 查看是否是在缓存周期内
     */
    public function checkUnionUserRate($unionid, $userid, $adminUnionUserid)
    {
        //查看更改的用户是否是公会下的
        $union_user_list = $this->model_user_union->isUnionUser($unionid, $userid);
        //公会信息
        $uninfo = $this->model_union->getUnionInfo($unionid);
        $data = [];
        $baseRate = 68;//对私主播默认比例
        do {
            if ($uninfo['un_user_id'] != $adminUnionUserid) {
                $code = Hint::ERR_FAIL;
                $msg = '非公会长,无权操作!';
                break;
            }
            if (empty($union_user_list)) {
                $code = Hint::ERR_FAIL;
                $msg = '非公会成员,无权操作!';
                break;
            }
            //取出redis的缓存
            $res = Redis::get($this->union_user_set_rate_key . $userid);
            if (!empty($res)) {
                $data['forbidden'] = 1;
                $data['rate'] = $res;
            } else {
                //没有缓存的话则取数据库配置信息
                $rateinfo = $this->model_user_union->getUnionUserRate($unionid, $userid, false);
                $data['forbidden'] = 0;
                $configMap = [];
                $config = $this->systemServices->get_config();
                foreach ($config as $k => $v) {
                    $value = $v['value'];
                    if ($v['type'] == 1) {
                        $value = intval($v['value']);
                    }
                    $configMap[$k] = $value;
                }
                $kk_to_diamond = $configMap['charm_to_kk'];
                $data['rate'] = !isset($rateinfo['rate']) && empty($rateinfo['rate']) ? $kk_to_diamond : $rateinfo['rate'];
            }
            $data['maxrate'] = $this->maxRate;
            $data['minRate'] = $this->minRate;
            $data['step'] = $this->rateStep;

            $code = Hint::SUCCESS;
            $msg = '获取成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 设置公会成员费率
     *
     * @param [int] $admin_uinonuser_id 工会长id
     * @param [int] $userid 成员id
     * @param [int] $union_id 公会id
     * @param [int] $user_rate 调整费率
     * @return array
     */
    public function setUinonUserRate($admin_uinonuser_id, $userid, $union_id, $user_rate)
    {
        //查看该公会是否是公会长id
        $uninfo = $this->model_union->getUnionInfo($union_id);
        $data = [];
        do {

            if (empty($uninfo)) {
                $code = Hint::ERR_FAIL;
                $msg = '公会不存在!';
                break;
            }
            //查看是否是对私公会
            if ($uninfo['settle_type'] != 1) {
                $code = Hint::ERR_FAIL;
                $msg = '必须是对私公会!';
                break;
            }
            if ($admin_uinonuser_id != $uninfo['un_user_id']) {
                $code = Hint::ERR_FAIL;
                $msg = '非公会长,无权操作!';
                break;
            }
            //查看更改的用户是否是公会下的
            $union_user_list = $this->model_user_union->getUnionUserList($union_id, '');
            $union_user_lists = array_column($union_user_list['user'], 'user_id');

            if (!in_array($userid, $union_user_lists)) {
                $code = Hint::ERR_FAIL;
                $msg = '非公会成员,无权操作!';
                break;
            }
            //判断范围
            if ($this->minRate > $user_rate || $this->maxRate < $user_rate) {
                $code = Hint::ERR_FAIL;
                $msg = '费率调整范围为 ' . $this->minRate . '% 到 ' . $this->maxRate . '% 之间';
                break;
            }

            //取出redis的缓存
            $res = Redis::get($this->union_user_set_rate_key . $userid);
            if (!empty($res)) {
                $code = Hint::ERR_FAIL;
                $msg = '一周内只能更改一次公会成员分成!';
                break;
            }
            //设置成员费率
            $setRate = $this->model_user_union->setUserRate($userid, $union_id, $user_rate);
            if ($setRate) {
                //给更改的用户发一条系统通知
                //获取用户信息
                $userInfo = $this->user->get_user_phone($userid);
                //手机号
                $userphone = $userInfo['mobile_phone'];
                $sendMsg = "您所属的公会【" . $uninfo['name'] . "】由会长将您的分成比例调整到" . $user_rate . "%,您确认后将立即调整";
                $sendNotice = $this->service_msg->sendSetUnionUserRateMsg($userid, $sendMsg, 'kkaudio://send_msg_action?type=0&phone=' . $userphone . '&title=' . urlencode($sendMsg));
                //设置一周缓存
                $userCache = Redis::set($this->union_user_set_rate_key . $userid, $user_rate);
                Redis::expire($this->union_user_set_rate_key . $userid, 7 * 86400);//一周缓存
            }
            $code = Hint::SUCCESS;
            $msg = '设置成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 公会成员对私确认-获取验证码
     *
     * @param [int] $userid
     * @return array
     */
    public function sendSmsCode($userid, $sms_token)
    {
        //获取用户信息
        $userInfo = $this->user->get_user_phone($userid);
        //手机号
        $userphone = $userInfo['mobile_phone'];
        $data = [];
        do {
            //获取init配置是否验证sms_token
            $alicodeConfig = $this->systemServices->getAliVerify();
            if ($alicodeConfig['status'] == 1) {
                if (empty($sms_token)) {
                    $code = Hint::CHECK_CAPTCHA_CODE_ERROR;
                    $msg = '系统检测您的版本过低,请升级最新版本';
                    break;
                }
                $cacheSms = Redis::get('ALI:VERIFY:TOKEN:' . $userphone);
                if (($cacheSms != md5($userphone)) || empty($cacheSms)) {
                    $code = Hint::CHECK_CAPTCHA_CODE_ERROR;
                    $msg = '图形验证码错误';
                    break;
                }
            }

            //每日次数限制
            if (!redis_num_lock('CACHE:MAX:SENDUNION:CODE:' . date("Ymd") . ':' . $userphone, 86400, 5)) {
                $code = Hint::NOT_ALLOW_SEND_CODE;
                $msg = '验证码每日限制最多5次!';
                break;
            }

            if (!redis_lock('SMS:UNION:' . $userphone, 60)) {
                $code = Hint::NOT_ALLOW_SEND_CODE;
                $msg = '获取验证码太频繁!';
                break;
            }
            //发送短信
            $expireTime = 60;
            $smsCode = randomkeys();
            $result = $this->smsService->spSendSingleSms($userphone, $smsCode);
            if ($result) {
                //redis 存储
                $redisKey = $this->smsPrefix . $userphone;
                Redis::set($redisKey, $smsCode);
                Redis::expire($redisKey, $expireTime);
            }
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 公会成员确认对私分成费率设置
     *
     * @param [int] $userid
     * @param [int] $smscode
     * @return array
     */
    public function confirmRate($userid, $smscode)
    {
        //获取用户信息
        $userInfo = $this->user->get_user_phone($userid);
        //手机号
        $userphone = $userInfo['mobile_phone'];
        $data = [];
        //校验验证码
        do {
            $sms_cache_code = Redis::get($this->smsPrefix . $userphone);
            if ($sms_cache_code != $smscode) {
                $code = Hint::SMS_CODE_ERROR;
                $msg = '验证码有误!';
                break;
            }
            //获取用户所在的公会信息
            $union_info = $this->model_user_union->userToUnion($userid, 3);

            $unionRateInfo = $this->model_user_union->getUnionUserRate($union_info['un_id'], $userid, false);
            //若已经确认过则提示
            if ($unionRateInfo['confirm_status']) {
                $code = Hint::ERROR;
                $msg = '您已确认过,无需确认!';
                break;
            }
            //查看创建时间是否大于三天
            $nowDate = Carbon::now()->toDateString();
            $diffDate = Carbon::parse($unionRateInfo['create_time'])->toDateString();
            $compare = Carbon::parse($diffDate)->diffInDays($nowDate, true);

            if ($compare > 3) {
                $code = Hint::ERROR;
                $msg = '确认失败，超过三日确认有效期!';
                break;
            }
            //更新费率表请求
            $this->model_user_union->confirmUnionRateByUser($union_info['un_id'], $userid);
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    //获取公会成员
    public function getAllUnionUserList($union_id)
    {
        $union_user_list = $this->model_user_union->getUnionUserList($union_id, '');
        $res['user'] = $union_user_list['user'];
        $res['role_user'] = $union_user_list['role_user'];
        return $res;
    }


    //离开公会
    public function quitMyUnion($user_id)
    {
        //获取用户公会
        $union_info = $this->model_user_union->userToUnion($user_id, 3);
        //公会房间
        $code = Hint::ERR_FAIL;
        $msg = '退出失败';
        $data = [];
        $role_arr = [2, 3, 4, 5, 6, 7];
        do {
            if (!$union_info) {
                $code = Hint::ERR_FAIL;
                $msg = '公会不存在';
                break;
            }
            $data['union_id'] = $union_info['un_id'];
            if ($union_info['un_user_id'] == $user_id && $union_info['role_id'] == 1) {
                $msg = '会长不可退出公会';
                break;
            }
            //查看身份
            if (in_array($union_info['role_id'], $role_arr)) {
                //管理位置  120小时
                $this->model_user_union->kickUser($user_id);
            }
            $union_room = $this->model_union->getUnionRoomIds($union_info['un_id']);

            foreach ($union_room as $v) {
                $this->model_room->del_role_join_room($v['room_id'], $user_id);
            }
            $res = $this->model_user_union->quitUserUnion($union_info['union_id'], $user_id);
            if ($res) {
                //删除用户代理
                $this->userAgentModel->agentUserDel($user_id);
                if (!empty($union_info['vest'])) {
                    $this->user->batchSetUnionVest(array($user_id), '', 0);
                }
                $code = Hint::SUCCESS;
                $msg = '退出成功';
                break;
            }
        } while (false);
        return compact('code', 'msg', 'data');
    }


    public function getRoleList()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('union_id', '公会id', 'int', true);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $union_id = $this->requestData['union_id'];
            $role_count_num = $this->model_user_union->unionRoleCountNum($union_id);
            $union_role_num = array_column($role_count_num, 'count_role', 'role_id'); //当前公会角色已有人数和对应角色上限人数
            $roles = $this->model_user_union->getRolesList();
            $role_total_num = array(0, 1, 3, 1, 1, 1, 1, 1);
            foreach ($roles as $k => &$v) {
                if ($k != 0) {
                    $temp['role_id'] = $k;
                    $temp['role_name'] = $v;
                    $temp['total_num'] = $role_total_num[$k];
                    if (isset($union_role_num[$k])) {
                        $temp['appoint_num'] = $union_role_num[$k];
                    } else {
                        $temp['appoint_num'] = 0;
                    }
                    $data[] = $temp;
                }
            }
        } while (false);
        return compact('code', 'msg', 'data');
    }

    /*
     * 审批入会
     * $user_id  审批人id
     * $apply_user_id  申请人id
     * $status  1同意 2拒绝
     * */
    public function editApplyUnionStatus($user_id, $apply_user_id, $status)
    {
        //查询用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        //验证用户权限
        $check_role = $this->model_user_union->checkUserRole($user_id, 1, $union_id);
        $check_room_role_type = $this->model_union->get_role($user_id);
        $code = Hint::ERR_FAIL;
        $msg = '审批失败';
        $data = [];
        do {
            if (!$union_info) {
                break;
            }
//            if ($check_role == 0) {
//            if ($check_room_role_type!=2 ||$check_role == 0) {
//                $code = Hint::ERR_FAIL;
//                $msg = '无权操作';
//                break;
//            }
            //查询用户是否存在公会中
            $apply_user_union = $this->model_user_union->userToUnion($apply_user_id, 1);
            if ($apply_user_union && $apply_user_union['un_id'] == $union_id) {
                $code = Hint::ERR_FAIL;
                $msg = '该用户已经是公会成员';
                break;
            }
            if ($apply_user_union && $apply_user_union['un_id'] != $union_id) {
                $code = Hint::ERR_FAIL;
                $msg = '该用户已经是其他公会成员';
                break;
            }
            //查询申请记录
            $apply_user_log = $this->model_user_union->applyUserLog($apply_user_id, $union_id);
            if (!$apply_user_log) {
                $code = Hint::ERR_FAIL;
                $msg = '审批失败';
                break;
            }
            if ($apply_user_log[0]['created_at'] < date('Y-m-d H:i:s', strtotime('-1 days'))) {
                $code = Hint::ERR_FAIL;
                $msg = '该申请已超时失效~';
                break;
            }

            if ($status == 1) {
                //判断是否实名验证
                $user_verify = $this->model_user_verify->getSuccess($apply_user_id);
                if (empty($user_verify)) {
                    $code = Hint::USER_NOT_CERTIFICATION;
                    break;
                }

                //同一实名身份证不可加入多个公会
                $user_verify_users = $this->model_user_verify->getAllIcCard($user_verify['idcard_number']);
                $user_ids = array_column($user_verify_users, 'user_id');
                $userUnionList = $this->model_union->getUserUnion($user_ids);
                if (!empty($userUnionList)) {
                    $unionIds = array_unique(array_column($userUnionList, 'un_id'));
                    if (count($unionIds) > 1 || !in_array($union_id, $unionIds)) {
                        $this->model_user_union->delApplyLogToStatus($apply_user_id);
                        $code = Hint::UNION_USER_EXIST;
                        $msg = '用户已入其他公会，审核失败';
                        break;
                    }
                }
            }
            //删除用户申请信息
//            $del_apply_user_log = $this->model_user_union->delApplyLogToUser($apply_user_id);
            //更新用户状态
            $del_apply_user_log = $this->model_user_union->updateApplyLogToUser($user_id, $apply_user_id, $status, $union_id);
            if (!$del_apply_user_log) {
                $code = Hint::ERR_FAIL;
                $msg = '审批失败';
                break;
            }
            if ($status == 2) {
                $this->model_user_union->delApplyLogToUser($apply_user_id);
                //拒绝
                $code = Hint::SUCCESS;
                $msg = '成功';
                $data['union_id'] = $union_id;
                break;
            }
            //添加公会成员
            $inserData['un_id'] = $union_id;
            $inserData['user_id'] = $apply_user_id;
            $inserData['role_id'] = 0;
            $create_union_user = $this->model_user_union->createUnionUser($inserData);
            if (!$create_union_user) {
                $code = Hint::ERR_FAIL;
                $msg = '审批失败';
                break;
            }
            //为公会成员设置马甲
            if (!empty($union_info['vest'])) {
                $this->user->batchSetUnionVest(array($apply_user_id), $union_info['vest'], 1);
            }
            $this->checkUserSetAgent($apply_user_id);
            $this->model_user_union->delApplyLogToStatus($apply_user_id);
            $code = Hint::SUCCESS;
            $msg = '成功';
            $data['union_id'] = $union_id;
            $data['user_id'] = $apply_user_id;
            $data['apply_user_id'] = $apply_user_id;
        } while (false);
        return compact('code', 'msg', 'data');
    }


    /*
     * 指定房间身份
     * $user_id  操作人id
     * $assign_user_id  指定人id
     * $role_type  0:普通用户 1：管理员 2：房主
     * */
    public function acceptRoomRole($user_id, $assign_user_id, $room_id, $role_type)
    {
        //获取用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 7, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '任命失败';
        $data = [];
        do {
            if (!$union_info) {
                break;
            }
            if ($check_role == 0) {
                $msg = '无权操作';
                break;
            }
            $union_room = $this->model_union->getUnionRoomIds($union_id);
            $union_room_ids = array_column($union_room, 'room_id');
            if (!in_array($room_id, $union_room_ids)) {
                $msg = '房间信息错误';
                break;
            }
            if ($role_type == 0) {
                $delRole = $this->model_room->del_role($room_id, $assign_user_id);
                if ($delRole) {
                    $code = Hint::SUCCESS;
                    $msg = '解除成功';
                    break;
                }
                break;
            }

            //查看分配用户是否已有权限
            $check_room_role_type = $this->model_room->get_role($room_id, $assign_user_id);
            if ($check_room_role_type == 1) {
                $msg = '对方已是房间内管理，请在房间将其管理身份取消后，再设置超管';
                break;
            }
            if ($check_room_role_type != 0) {
                $msg = '已有权限';
                break;
            }
            //查询房间权限人数
            $room_role_num = $this->model_room->get_roles_all_count($room_id);
            $room_role_num = array_column($room_role_num, null, 'role_type');
            $num_res = true;
            $num = $room_role_num[$role_type]['count_role_id'];
            switch ($role_type) {
                case 1:
                    if ($num > 2) {
                        $num_res = false;
                        break;
                    }
                    break;
                case 2:
                    if ($num > 2) {
                        $num_res = false;
                        break;
                    }
                    break;
            }
            if (!$num_res) {
                $msg = '管理员人数达到上限';
                break;
            }
            //添加房间角色
            $res = $this->model_room->add_role($room_id, $assign_user_id, $role_type);
            $this->model_union->updateUnionRole($union_id, $assign_user_id, 2);
            if (!$res) {
                break;
            }

            //发送任命通知消息
            $this->service_room_msg->sendRoomRoleListMsg($room_id, 1, $assign_user_id);

            $code = Hint::SUCCESS;
            $msg = '任命成功';
        } while (false);
        return compact('code', 'msg', 'data');
    }

    //踢出公会
    public function kickUnionUser($user_id, $kick_user_id)
    {
        //获取用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 2, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '踢出失败';
        $data = [];
        do {
            if ($user_id == $kick_user_id) { //不允许踢出自己
                break;
            }
            if (!$union_info) {
                break;
            }
            if ($check_role == 0) {
                $msg = '无权操作';
                break;
            }
            $kick_user_union = $this->model_user_union->userToUnion($kick_user_id, 1);//踢出用户公会信息

            if (!$kick_user_union || $kick_user_union['un_id'] != $union_id) {
                break;
            }
            if ($union_info['un_user_id'] == $kick_user_id) {//不允许踢出会长
                break;
            }
            //不可跨级同级i提出

            if ($union_info['role_id'] >= $kick_user_union['role_id'] && $kick_user_union['role_id'] != 0) {
                break;
            }
            //踢出公会
            if ($kick_user_union['role_id'] != 0) {
                $this->model_user_union->kickUser($kick_user_id);

            }
            //删除用户信息
            $res = $this->model_user_union->quitUserUnion($union_id, $kick_user_id);
            $this->model_user_union->delApplyLogToUser($kick_user_id);
            if (!$res) {
                break;
            }
            //删除用户代理
            $this->userAgentModel->agentUserDel($kick_user_id);
            //删除公会成员马甲
            if (!empty($union_info['vest'])) {
                $this->user->batchSetUnionVest(array($kick_user_id), '', 0);
            }
            $union_room = $this->model_union->getUnionRoomIds($union_info['un_id']);
            foreach ($union_room as $v) {
                $this->model_room->del_role_join_room($v['room_id'], $kick_user_id);
            }
            $code = Hint::SUCCESS;
            $msg = '踢出成功';
            $data['union_id'] = $union_id;
            break;

        } while (false);
        return compact('code', 'msg', 'data');
    }


    public function myUnionUrl($user_id)
    {
        return $this->model_user_union->userToUnion($user_id, 3);
    }

    public function myApplyUnion($user_id, $union_id)
    {
        return $this->model_user_union->applyUserLog($user_id, $union_id);
    }


    //跟新公会细则
    public function updateRule($user_id)
    {
        $union_info = $this->model_user_union->userToUnion($user_id, 0);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $code = Hint::ERR_FAIL;
        $msg = '失败';
        $data = [];
        do {
            if (!$union_info) {
                break;
            }
            //修改公会rule
            $res = $this->model_union->updateRule($union_id);
            if (!$res) {
                break;
            }
            $code = Hint::SUCCESS;
            $msg = '成功';
            $data['union_id'] = $union_id;
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }


    public function cancelUnionRoomRole($user_id, $cancel_user_id, $room_id)
    {
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 7, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '失败';
        $data = [];
        do {
            if (!$union_info) {
                break;
            }
            if ($check_role == 0) {
                $msg = '无权操作';
                break;
            }
            if ($user_id == $cancel_user_id) {
                break;
            }
            //查看公会房间
            $union_rooms = $this->model_union->getUnionRoomIds($union_id);
            $union_room_ids = array_column($union_rooms, 'room_id');
            if (!in_array($room_id, $union_room_ids)) {
                break;
            }

            //修改公会房间role
            $res = $this->model_room->del_role_join_room($room_id, $cancel_user_id);
            if (!$res) {
                break;
            }
            $this->model_union->updateUnionRole($union_id, $cancel_user_id, 0);
            //发送取消任命通知消息
            $this->service_room_msg->sendRoomRoleListMsg($room_id, 0, $cancel_user_id);

            $code = Hint::SUCCESS;
            $msg = '成功';
            $data['union_id'] = $union_id;
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    //公会房间
    public function getUnionRoom($user_id, $startDay, $endDay, $Daytype, $page, $page_size)
    {
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $code = Hint::SUCCESS;
        $msg = '数据加载完成';
        $data['list'] = [];
        if (empty($startDay)) {
            if ($Daytype == 1) {
                $day = date('Y-m-d', time());
                $startDay = $day;
                $endDay = $day;
            } elseif ($Daytype == 2) {
                $startDate = date('Y-m-d', strtotime('this week monday'));
                //// 获取当前周的最后一天（默认为星期日）
                $endDate = date('Y-m-d', strtotime('this week sunday'));
                $startDay = $startDate;
                $endDay = $endDate;
            } elseif ($Daytype == 3) {
                // 获取当前月的第一天
                $firstDayOfMonth = date('Y-m-01');
                // 获取当前月的最后一天
                $lastDayOfMonth = date('Y-m-t');
                $startDay = $firstDayOfMonth;
                $endDay = $lastDayOfMonth;
            }
        }
        do {
            if (!$union_info) {
                break;
            }
            $union_id = $union_info['un_id'];
            //查看公会房间id
            $union_rooms = $this->model_union->getUnionRoomIdsV2($union_id, $page, $page_size);

            if (!$union_rooms) {
                break;
            }

            //读取房间积分
            $roomScoreModel = new RoomScore();
            $roomIds = array_column($union_rooms, 'room_id');
            $scoreMap = $roomScoreModel->getReputationByRoomIds($roomIds);
//	     $room_consumerv2=$this->model_union->getUnionFinanceALLV2($union_info['un_id'],$startDay,$endDay);
//          foreach ($room_consumer as $uu=>$uuv){}

            foreach ($union_rooms as $k => &$v) {
                $v['image'] = build_image($v['image']);
                $role = $this->model_room->get_roles_all_by_role_type($v['room_id'], 2);
//                $roleMap = array_column($role,'role_type','user_id');
//                if($union_info['role_id'] != 1 && !isset($roleMap[$user_id])){
//                    //如果不是房主，且自己不是房间超管，则删掉
//                    unset($union_rooms[$k]);
//                    continue;
//                }

                if ($role) {
                    foreach ($role as &$vv) {
                        $vv['portrait'] = build_image(json_decode($vv['portrait'])[0]);
                    }

                    $v['role_user_list'] = $role; //房间管理员列表
//                    $v['role_user_list'] = []; //房间管理员列表
                    $v['role_user_entrance'] = $union_info['role_id'] == 1 ? 1 : 0; //是否显示【房间管理】入口

                }
                $opened = $this->model_room->get_opened($v['room_id']);
                if ($opened) {
                    $v['opened'] = true;
                } else {
                    unset($union_rooms[$k]);
                    $v['opened'] = false;
                }
                //房间信誉分
                $v['reputation'] = $scoreMap[$v['room_id']] ?? $roomScoreModel::DEFAULT_REPUTATION;
                //默认名称
                if (empty($v['name'])) {
                    $v['name'] = Room::DEFAULT_ROOM_NAME;
                }

//                //房间流水
//                    $room_consumer = $this->model_union->getUnionRoomFinanceALL($v['room_id'], $startDay, $endDay);
                $v['room_consumer'] = '';
            }

            $union_rooms = array_merge($union_rooms);
            $code = Hint::SUCCESS;
            $msg = '成功';
            $data['list'] = empty($union_rooms) ? [] : $union_rooms;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //公会房间总流水
    public function getUnionRoomTotalStream($room_id)
    {
        $unionInfo = $this->model_union->getUnionByRoomId($room_id);
        $code = Hint::SUCCESS;
        $msg = '数据加载完成';
        $data['consumer'] = '';
        do {
            $room_consumer = $this->model_union->getUnionRoomFinanceTotal($unionInfo['id'], $room_id, '', '');
            $data['consumer'] = $room_consumer['total'] ?? "0";
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //公会流水
    public function getUnionRoomV2($user_id, $startDay, $endDay, $Daytype)
    {
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $code = Hint::ERR_FAIL;
        $msg = '数据为空';
        $data = [];

//        if($startDay==$endDay){
//            $Daytype='1';
//        }
        if (empty($startDay)) {
            if ($Daytype == 1) {
                $day = date('Y-m-d', time());
                $startDay = $day;
                $endDay = $day;
            } elseif ($Daytype == 2) {
                $startDate = date('Y-m-d', strtotime('this week monday'));
                //// 获取当前周的最后一天（默认为星期日）
                $endDate = date('Y-m-d', strtotime('this week sunday'));
                $startDay = $startDate;
                $endDay = $endDate;
            } elseif ($Daytype == 3) {
                // 获取当前月的第一天
                $firstDayOfMonth = date('Y-m-01');
                // 获取当前月的最后一天
                $lastDayOfMonth = date('Y-m-t');
                $startDay = $firstDayOfMonth;
                $endDay = $lastDayOfMonth;
            }
        }
        do {
            if (!$union_info) {
                break;
            }
            $union_id = $union_info['un_id'];
            //查看公会房间id
            $union_rooms = $this->model_union->getUnionRoomIdsList($union_id, $startDay, $endDay);
//            if (!$union_rooms) {
//                break;
//            }
            //读取房间积分
            $roomScoreModel = new RoomScore();
            $roomIds = array_column($union_rooms, 'room_id');
            $scoreMap = $roomScoreModel->getReputationByRoomIds($roomIds);
            $room_consumerv2 = $this->model_union->getUnionFinanceALLV2($union_info['un_id'], $startDay, $endDay);
            foreach ($union_rooms as $k => &$v) {
                $v['image'] = build_image($v['image']);
                $role = $this->model_room->get_roles_all_by_role_type($v['room_id'], 2);
                $roleMap = array_column($role, 'role_type', 'user_id');
//                if($union_info['role_id'] != 1 && !isset($roleMap[$user_id])){
//                    //如果不是房主，且自己不是房间超管，则删掉
//                    unset($union_rooms[$k]);
//                    continue;
//                }
                if ($role) {
                    foreach ($role as &$vv) {
                        $vv['portrait'] = build_image(json_decode($vv['portrait'])[0]);
                    }
//                    $v['role_user_list'] =[]; //房间管理员列表
                    $v['role_user_list'] = $role; //房间管理员列表
                    $v['role_user_entrance'] = $union_info['role_id'] == 1 ? 1 : 0; //是否显示【房间管理】入口
                }
                $opened = $this->model_room->get_opened($v['room_id']);
                if ($opened) {
                    $v['opened'] = true;
                } else {
                    $v['opened'] = false;
                }
                //房间信誉分
                $v['reputation'] = $scoreMap[$v['room_id']] ?? $roomScoreModel::DEFAULT_REPUTATION;
                //默认名称
                if (empty($v['name'])) {
                    $v['name'] = Room::DEFAULT_ROOM_NAME;
                }

//                //房间流水
//                $room_consumer = $this->model_union->getUnionRoomFinanceALL($v['room_id'], $startDay, $endDay);
                $v['room_consumer'] = $v['total'] ?? "0";
                $day = date('Y-m-d H:i:s', time());
            }
//                每小时流水
            write_log('room', "$union_info[un_id],$day");
            $union_hour_consumer = $this->model_union->getHourUnionBill($union_info['un_id'], $day);
            $union_day_consumer = $this->model_union->getDayUnionBill($union_info['un_id'], $startDay, $endDay);
            $union_rooms = array_merge($union_rooms);

            $data['list'] = empty($union_rooms) ? [] : $union_rooms;
            if ($union_info['role_id'] == 1 || isset($roleMap[$user_id])) {
                $data['consumer'] = empty($room_consumerv2) ? "0" : $room_consumerv2;

                if ($Daytype == 1) {
                    $data['daytype'] = $Daytype;
                    $hours = [];
                    for ($i = 0; $i < 24; $i++) {
                        array_push($hours, $i);
                    }
                    foreach ($hours as $hour) {
                        $res = array_column(objToArray($union_hour_consumer), null, 'time');
                        $data['union_hour_consumer']['time'] = "$hour";
                        $data['union_hour_consumer']['total'] = empty($res[$hour]['total']) ? "0" : $res[$hour]['total'];
                        $data2[] = $data['union_hour_consumer'];
                    }
                    $data['union_hour_consumer'] = empty($data2) ? [] : $data2;
                } else {
                    $now = time();
                    $timeBase = '2024-05-01';
                    //项目起始日期
                    if (empty($startDay) || (!empty($startDay) && strtotime($startDay) < strtotime($timeBase))) {
                        $starttime = $timeBase;
                    }
                    if (empty($endDay) || (!empty($endDay) && strtotime($endDay) > $now)) {
                        $endtime = date("Y-m-d", $now);
                    }
                    $starttime = strtotime($startDay);
                    $endtime = strtotime($endDay);
                    if ($Daytype == 3) {
                        $starttime = strtotime(date('Y-m-01', $starttime));
                    } else {
                        $starttime = strtotime(date('Y-m-d', $starttime));
                    }
                    while ($starttime <= $endtime) {
                        $list[] = date('m-d', $starttime);
                        $starttime = $starttime + 86400;
                    }
                    foreach ($list as $date) {
                        $res = array_column(objToArray($union_day_consumer), null, 'time');
                        foreach ($union_day_consumer as $kkk => $vvv) {
                        }
                        $data['union_hour_consumer']['time'] = $date;
                        $data['union_hour_consumer']['total'] = empty($res[$date]['total']) ? "0" : $res[$date]['total'];
                        $data2[] = $data['union_hour_consumer'];
                    }
                    $data['union_hour_consumer'] = empty($data2) ? [] : $data2;

                }
            } else {
                $data['union_hour_consumer'] = [];
                $data['consumer'] = "0";
            }
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function getUnionRoomV2Days($user_id, $startDay, $endDay, $Daytype)
    {
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $code = Hint::ERR_FAIL;
        $msg = '数据为空';
        $data = [];

        if ($startDay == $endDay && trim($startDay) && trim($endDay)) {
            $Daytype = '1';
        }
        if (empty($startDay)) {
            if ($Daytype == 1) {
                $day = date('Y-m-d', time());
                $startDay = $day;
                $endDay = $day;
            } elseif ($Daytype == 2) {
                $startDate = date('Y-m-d', strtotime('this week monday'));
                //// 获取当前周的最后一天（默认为星期日）
                $endDate = date('Y-m-d', strtotime('this week sunday'));
                $startDay = $startDate;
                $endDay = $endDate;
            } elseif ($Daytype == 3) {
                // 获取当前月的第一天
                $firstDayOfMonth = date('Y-m-01');
                // 获取当前月的最后一天
                $lastDayOfMonth = date('Y-m-t');
                $startDay = $firstDayOfMonth;
                $endDay = $lastDayOfMonth;
            }
        }
        do {
            if (!$union_info) {
                break;
            }
            $union_id = $union_info['un_id'];


            if (strtotime($endDay) >= strtotime(date('Y-m-d'))) {
                $todayList = $this->model_union->getDayUnionBillToday($union_info['un_id'], $startDay, $endDay);
            }


            //查看公会房间id
            if ($Daytype == '1') {
                $union_rooms = $this->model_union->getUnionRoomIdsList($union_id, $startDay, $endDay);
            } else {
                $union_rooms = $this->model_union->getUnionRoomIdsListDays($union_id, $startDay, $endDay);
                // write_log('roomDays', var_export($union_rooms, true), []);
                if (count($union_rooms) && count($todayList)) {
                    foreach ($union_rooms as &$room) {
                        foreach ($todayList as $td) {
                            if (
                                $room['union_id'] == $td['union_id']
                                && $room['room_id'] == $td['room_id']
                            ) {
                                $room['total'] += $td['total'];
                            }
                        }
                    }
                }
                unset($room);
                // write_log('roomDays', var_export($union_rooms, true), []);
            }


            //读取房间积分
            $roomScoreModel = new RoomScore();
            $roomIds = array_column($union_rooms, 'room_id');
            $scoreMap = $roomScoreModel->getReputationByRoomIds($roomIds);
            if ($Daytype == '1') {
                $room_consumerv2 = $this->model_union->getUnionFinanceALLV2($union_info['un_id'], $startDay, $endDay);
            } else {
                $room_consumerv2 = $this->model_union->getUnionFinanceALLV2Days($union_info['un_id'], $startDay, $endDay);
                if (strtotime($endDay) >= strtotime(date('Y-m-d'))) {
                    $room_consumerv2 += $this->model_union->getUnionFinanceALLV2Today($union_info['un_id'], $startDay, $endDay);
                }
            }
            foreach ($union_rooms as $k => &$v) {
                $room = DB::table('room')->where('room_id', $v['room_id'])->first();
                write_log('daytypeV2', 'room', ['room' => $v['room_id']]);
                $v['image'] = build_image($room->image);
                $v['name'] = $room->name;
                $v['room_uid'] = $room->room_uid;
                $role = $this->model_room->get_roles_all_by_role_type($v['room_id'], 2);
                $roleMap = array_column($role, 'role_type', 'user_id');
//                if($union_info['role_id'] != 1 && !isset($roleMap[$user_id])){
//                    //如果不是房主，且自己不是房间超管，则删掉
//                    unset($union_rooms[$k]);
//                    continue;
//                }
                if ($role) {
                    foreach ($role as &$vv) {
                        $vv['portrait'] = build_image(json_decode($vv['portrait'])[0]);
                    }
//                    $v['role_user_list'] =[]; //房间管理员列表
                    $v['role_user_list'] = $role; //房间管理员列表
                    $v['role_user_entrance'] = $union_info['role_id'] == 1 ? 1 : 0; //是否显示【房间管理】入口
                }
                $opened = $this->model_room->get_opened($v['room_id']);
                if ($opened) {
                    $v['opened'] = true;
                } else {
                    $v['opened'] = false;
                }
                //房间信誉分
                $v['reputation'] = $scoreMap[$v['room_id']] ?? $roomScoreModel::DEFAULT_REPUTATION;
                //默认名称
                if (empty($v['name'])) {
                    $v['name'] = Room::DEFAULT_ROOM_NAME;
                }

//                //房间流水
//                $room_consumer = $this->model_union->getUnionRoomFinanceALL($v['room_id'], $startDay, $endDay);
                $v['room_consumer'] = $v['total'] ?? "0";
                $day = date('Y-m-d H:i:s', time());
            }
//                每小时流水
            // write_log('roomDays', "$union_info[un_id],$day", []);
            $union_hour_consumer = $this->model_union->getHourUnionBill($union_info['un_id'], $day);
            if ($Daytype == '1') {
                $union_day_consumer = $this->model_union->getDayUnionBill($union_info['un_id'], $startDay, $endDay);
            } else {
                $union_day_consumer = $this->model_union->getDayUnionBillDays($union_info['un_id'], $startDay, $endDay);
                if (count($union_rooms) && count($union_day_consumer)) {
                    foreach ($union_rooms as &$room) {
                        foreach ($union_day_consumer as $td) {
                            if (
                                $room['union_id'] == $td['union_id']
                                && $room['room_id'] == $td['room_id']
                            ) {
                                $room['total'] += $td['total'];
                            }
                        }
                    }
                }
                unset($room);
            }


            $union_rooms = array_merge($union_rooms);
            $data['list'] = empty($union_rooms) ? [] : $union_rooms;
            if ($union_info['role_id'] == 1 || isset($roleMap[$user_id])) {
                $data['consumer'] = empty($room_consumerv2) ? "0" : $room_consumerv2;

                if ($Daytype == 1) {
                    $data['daytype'] = $Daytype;
                    $hours = [];
                    for ($i = 0; $i < 24; $i++) {
                        array_push($hours, $i);
                    }
                    foreach ($hours as $hour) {
                        $res = array_column(objToArray($union_hour_consumer), null, 'time');
                        $data['union_hour_consumer']['time'] = "$hour";
                        $data['union_hour_consumer']['total'] = empty($res[$hour]['total']) ? "0" : $res[$hour]['total'];
                        $data2[] = $data['union_hour_consumer'];
                    }
                    $data['union_hour_consumer'] = empty($data2) ? [] : $data2;
                } else {
                    $now = time();
                    $timeBase = '2024-05-01';
                    //项目起始日期
                    if (empty($startDay) || (!empty($startDay) && strtotime($startDay) < strtotime($timeBase))) {
                        $starttime = $timeBase;
                    }
                    if (empty($endDay) || (!empty($endDay) && strtotime($endDay) > $now)) {
                        $endtime = date("Y-m-d", $now);
                    }
                    $starttime = strtotime($startDay);
                    $endtime = strtotime($endDay);
                    if ($Daytype == 3) { //任意日期
                        $starttime = strtotime(date('Y-m-01', $starttime));
                    } else {  //周
                        $starttime = strtotime(date('Y-m-d', $starttime));
                    }
                    while ($starttime <= $endtime) {
                        $list[] = date('m-d', $starttime);
                        $starttime = $starttime + 86400;
                    }
                    foreach ($list as $date) {
                        $res = array_column(objToArray($union_day_consumer), null, 'time');
                        foreach ($union_day_consumer as $kkk => $vvv) {
                        }
                        $data['union_hour_consumer']['time'] = $date;
                        $data['union_hour_consumer']['total'] = empty($res[$date]['total']) ? "0" : $res[$date]['total'];
                        $data2[] = $data['union_hour_consumer'];
                    }
                    $data['union_hour_consumer'] = empty($data2) ? [] : $data2;

                }
            } else {
                $data['union_hour_consumer'] = [];
                $data['consumer'] = "0";
            }
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);

        return compact('code', 'msg', 'data');
    }


    //解散公会
    public function delUnion($user_id)
    {
        //获取用户公会
        $union_info = $this->model_user_union->userToUnion($user_id, 3);
        //公会房间
        $code = Hint::SUCCESS;
        $msg = '解散成功';
        $data = [];
        do {
            if (!$union_info) {
                $code = Hint::ERR_FAIL;
                $msg = '公会不存在';
                break;
            }
            $data['union_id'] = $union_info['un_id'];
            if ($union_info['un_user_id'] == $user_id && $union_info['role_id'] == 1) {
                DB::beginTransaction();
                try {
                    //删除公会信息
                    $this->model_union->delUnion($union_info['un_id'], $user_id);
                    $this->model_union->delUnionRoom($union_info['un_id']);

                    //公会成员
                    $users = $this->model_user_union->getUserNum($union_info['un_id'], false);
                    $user_ids = array_column($users, 'user_id');

                    //删除公会成员马甲
                    if (!empty($union_info['vest'])) {
                        $this->user->batchSetUnionVest($user_ids, '', 0);
                    }
                    //解散公会成员
                    $res = $this->model_user_union->quitUserUnion($union_info['union_id']);
                    if (!$res) {
                        DB::rollBack();
                        $code = Hint::ERR_FAIL;
                        $msg = '解散公会失败';
                        break;
                    }

                    //删除用户代理
                    $this->userAgentModel->agentUserDelList($user_ids);

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    $code = Hint::ERROR;
                    $msg = '更新系统异常';
                    break;
                }

                $this->model_union_rank->delContribution($data['union_id']);
            }
        } while (false);
        return compact('code', 'msg', 'data');
    }

    public function checkJoinUnionToUser($user_id, $union_id)
    {
        $is_apply = $this->model_user_union->applyUserLog($user_id, $union_id);
        $is_union = $this->model_user_union->userToUnion($user_id, 3);
        $res['inner_status'] = 0;
        if (!$is_union) {
            if ($is_apply) {
                $res['inner_status'] = 3;
            }
        } else {
            if ($is_union['un_id'] == $union_id) {
                $res['inner_status'] = 1;
            }
            if ($is_union['un_id'] != $union_id) {
                $res['inner_status'] = 2;
            }
        }
        return $res;
    }

    //查看公会流水
    public function showUnionRoomFinance($user_id, $room_id, $startDay, $endDay, $search_user_id)
    {
        //获取用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 8, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '查看失败';
        do {
            if (!$union_info) {
                break;
            }
            if ($check_role == 0) {
                $msg = '无权操作';
                break;
            }
            $union_rooms_ids_arr = [];
            //查看公会房间id
            $union_rooms_ids = $this->model_union->getUnionRoomIds($union_id);
            if ($union_rooms_ids) {
                $union_rooms_ids_arr = array_column($union_rooms_ids, 'room_id');
            }
            if ($room_id) {
                $room_ids[] = $room_id;
            } else {
                $room_ids = $union_rooms_ids_arr;
            }
            $monthStartDay = date('Y-m-01 00:00:00', time());
            $monthEndDay = date('Y-m-t 23:59:59', time());
            //统计房间日流水
            $consumer_rooms_day = $this->FinanceRoomWealth->getRoomWealthBuyRoomIds($room_ids, $startDay, $endDay, $search_user_id);
            $data['day_finance'] = abs(array_sum(array_column($consumer_rooms_day, 'diamond_value')));
            $consumer_rooms_month = $this->FinanceRoomWealth->getRoomWealthBuyRoomIds($union_rooms_ids_arr, $monthStartDay, $monthEndDay, '');
            $data['month_finance'] = abs(array_sum(array_column($consumer_rooms_month, 'diamond_value')));
            //房间消费人数
            $consumer_user_day = $this->FinanceRoomWealth->getRoomWealthConsumerUser($room_ids, $startDay, $endDay, $search_user_id);
            $data['consumer_user'] = count($consumer_user_day);
            $wallet = $this->userWallet->get_wallet($user_id);
            $data['kk_balance'] = $wallet['kk_balance'];
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    //查看公会流水
    public function showUnionRoomFinanceV2($user_id)
    {
        //获取用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 8, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '查看失败';
        do {
            if (!$union_info) {
                break;
            }
            if ($check_role == 0) {
                $msg = '无权操作';
                break;
            }

            //统计房间日流水
            list($data['day_finance'], $data['month_finance']) = $this->FinanceRoomWealth->getTotalRoomWealthByRoomIds($union_id);
            $wallet = $this->userWallet->get_wallet($user_id);
            $data['kk_balance'] = $wallet['kk_balance'];
            $data['desc'] = "*如有疑问请咨询官方客服人员";
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 统计公会结算流水
     * @param $user_id 用户id
     * @return array
     */
    public function showUnionRoomBill($user_id, $startDate, $endDate, $roomid)
    {
        //获取用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 8, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '查看失败';
        $permisson = true;
        if (!empty($room_id)) {
            $permisson = $this->showRoomFinanceStream($user_id, $room_id);
        }
        $data = [];
        do {
            if (!$union_info) {
                break;
            }
            if ($check_role == 0 && !$permisson) {
                $msg = '无权操作';
                break;
            }
            //统计房间结算流水
            $allbill = $this->model_union->showUnionRoomBill($startDate, $endDate, $roomid, $union_id);
            $data = $allbill;
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    public function showUnionConsumerLog($user_id, $room_id, $startDay, $endDay, $search_user_id, $page = 1, $limit = 20)
    {
        //获取用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 8, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '查看失败';
        $startTime = strtotime($startDay);
        $endTime = strtotime($endDay);
        $permisson = true;
        if (!empty($room_id)) {
            $permisson = $this->showRoomFinanceStream($user_id, $room_id);
        }
        do {

            if (!$union_info) {
                break;

            }
            if ($endTime - $startTime > 5184000) {
                $msg = '请查询60天内数据';
                break;
            }
            if ($check_role == 0 && !$permisson) {
                $msg = '无权操作';
                break;
            }

            //查看公会房间id
            if ($room_id > 0) {
                $room_info = $this->model_room->get_room($room_id);
                if (empty($room_info)) {
                    $msg = '房间不存在';
                    break;
                }
            }

            //房间消费流水
            $res = $this->FinanceRoomWealth->getRoomConsumerUserLog($union_id, $room_id, $startDay, $endDay, $search_user_id, $page, $limit);
            //读取房间消费总数
            $total_diamond = $this->FinanceRoomWealth->getRoomConsumerTotalValue($union_id, $room_id, $startDay, $endDay);
            if (count($res) > 0) {
                //读取用户信息
                $userIds = array_merge(array_unique(array_column($res, 'from_user_id')));
                $v_user_info = $this->user->get_users_by_ids($userIds);
                $usersMap = array_column($v_user_info, null, 'user_id');

                //读取房间信息
                $roomIds = array_merge(array_unique(array_column($res, 'room_id')));
                $v_room_info = $this->model_room->get_rooms_by_ids($roomIds);
                $roomsMap = array_column($v_room_info, null, 'room_id');

                foreach ($res as &$v) {
                    try {
                        $v['nickname'] = $usersMap[$v['from_user_id']]['nickname'] ?? '';
                        $v['user_uid'] = $usersMap[$v['from_user_id']]['user_uid'] ?? '';
                        $v['image'] = build_image($usersMap[$v['from_user_id']]['images'][0] ?? '');
                        $v['name'] = $roomsMap[$v['room_id']]['name'] ?? '';
                        $v['room_uid'] = $roomsMap[$v['room_id']]['room_uid'] ?? '';
                        $v['diamond_value'] = abs($v['diamond_value']);
                        $v['year'] = substr(date('Y-m-d', $v['create_timestamp']), 0, 4);
                        $v['month'] = substr(date('Y-m-d', $v['create_timestamp']), 5, 10);
                    } catch (\Exception $exception) {
                        write_log('showUnionConsumerLog', 'showUnionConsumerLog Error', $exception->getMessage());
                        continue;
                    }
                }
            }
            $data['total'] = $total_diamond;
            $data['list'] = $res;
            $data['show_name'] = empty($room_id) ? '公会总流水（钻石）' : $room_info['name'] . ' 总流水（钻石）';
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function showRoomFinanceStream($userId, $roomId)
    {
        if ($roomId <= 0 || $userId <= 0) {
            return false;
        }
        $role = $this->model_room->get_role($roomId, $userId);
        if ($role == 0) {
            return false;
        }

        $config = (new SystemConfig())->getUnionConsumerLogShowConfig();

        if ($role == 1) {
            return $config[1] > 0;
        }
        //超管或者房主
        return $config[0] > 0;

    }

    public function showUnionConsumerLogByReceiveUserV2($user_id, $room_id, $startDay, $endDay, $search_user_id, $page, $limit, $Daytype)
    {
        //获取用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 8, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '查看失败';
        $startTime = strtotime($startDay);
        $endTime = strtotime($endDay);
        if (!empty($startDay)) {
            $startDay = $startDay . '00:00:00';
            $endDay = $endDay . '23:59:59';
        }
        if ($Daytype == 1) {
            $day = date('Y-m-d', time());
            $startDay = $day . ' 00:00:00';
            $endDay = $day . ' 23:59:59';
        } elseif ($Daytype == 2) {
            $startDate = date('Y-m-d', strtotime('this week monday'));
            //// 获取当前周的最后一天（默认为星期日）
            $endDate = date('Y-m-d', strtotime('this week sunday'));
            $startDay = $startDate . ' 00:00:00';
            $endDay = $endDate . ' 23:59:59';
        } elseif ($Daytype == 3) {
            // 获取当前月的第一天
            $firstDayOfMonth = date('Y-m-01');
            // 获取当前月的最后一天
            $lastDayOfMonth = date('Y-m-t');
            $startDay = $firstDayOfMonth . ' 00:00:00';
            $endDay = $lastDayOfMonth . ' 23:59:59';
        }
        $permisson = true;
        if (!empty($room_id)) {
            $permisson = $this->showRoomFinanceStream($user_id, $room_id);
        }
        do {
            if (!$union_info) {
                break;
            }
            if ($endTime - $startTime > 5184000) {
                $msg = '请查询60天内数据';
                break;
            }
            if ($check_role == 0 && !$permisson) {
                $msg = '无权操作';
                break;
            }
            //查看公会房间id
            if ($room_id) {
                $room_info = $this->model_room->get_room($room_id);
                if (empty($room_info)) {
                    $msg = '房间不存在';
                    break;
                }
            }
            $day = date('Y-m-d H:i:s', time());
            $HourRoomBill = $this->model_union->getHourRoomBill($room_id, $day);
            $start = microtime(true);
            $dayRoomBill = $this->model_union->getdayRoomBillDays($room_id, $startDay, $endDay);
            write_log('groom', $endDay, ['room_id' => $room_id, 'roomtotal' => $dayRoomBill]);
            if (strtotime($endDay) >= strtotime(date('Y-m-d'))) {
                $todayList = $this->model_union->getdayRoomBillToday($room_id, $startDay, $endDay);
                if (!empty($todayList)) {
                    if (empty($dayRoomBill)) {
                        $dayRoomBill = $todayList;
                    } else {
                        $mergedList = [];
                        $keyedTodayList = [];

                        // Create lookup array for today's list
                        foreach ($todayList as $today) {
                            $key = $today['room_id'] . '_' . $today['time'];
                            $keyedTodayList[$key] = $today;
                        }

                        // Process dayRoomBill and merge with today's data
                        foreach ($dayRoomBill as $day) {
                            $key = $day['room_id'] . '_' . $day['time'];
                            if (isset($keyedTodayList[$key])) {
                                $day['total'] += $keyedTodayList[$key]['total'];
                                unset($keyedTodayList[$key]);
                            }
                            $mergedList[] = $day;
                        }

                        // Add remaining today records if any
                        foreach ($keyedTodayList as $today) {
                            $mergedList[] = $today;
                        }

                        $dayRoomBill = $mergedList;
                    }
                }
            }

            $end = microtime(true);
            write_log('getdayRoomBill', 'api exec time:', ($end - $start) * 1000);            //房间消费流水
            //房间消费流水
            $res = $this->FinanceRoomWealth->getRoomConsumerUserLogBySendUser($union_id, $room_id, $startDay, $endDay, $page, $limit);

            //读取房间总数
            $total_diamond = $this->FinanceRoomWealth->getRoomConsumerTotalValue($union_id, $room_id, $startDay, $endDay);
            if (count($res) >= 0) {

                //读取用户信息
                $userIds = array_merge(array_unique(array_column($res, 'user_id')));
                $v_user_info = $this->user->get_users_by_ids($userIds);
                $usersMap = array_column($v_user_info, null, 'user_id');

                //读取房间信息
                $roomIds = array_merge(array_unique(array_column($res, 'room_id')));
                $v_room_info = $this->model_room->get_rooms_by_ids($roomIds);
                $roomsMap = array_column($v_room_info, null, 'room_id');

                foreach ($res as &$v) {
                    $v['nickname'] = $usersMap[$v['user_id']]['nickname'] ?? '';
                    $v['user_uid'] = $usersMap[$v['user_id']]['user_uid'] ?? '';
                    $v['image'] = build_image($usersMap[$v['user_id']]['images'][0] ?? '');
                    $v['name'] = $roomsMap[$v['room_id']]['name'] ?? '';
                    $v['room_uid'] = $roomsMap[$v['room_id']]['room_uid'] ?? '';
                    $v['diamond_value'] = abs($v['diamond_value']);
                    $v['year'] = substr(date('Y-m-d', $v['create_timestamp']), 0, 4);
                    $v['month'] = substr(date('Y-m-d', $v['create_timestamp']), 5, 10);
                }
            }
//            $data['total'] = $total_diamond;
            $data['total'] = array_sum(array_column($dayRoomBill, 'total')) ?? 0;
            $data['list'] = $res;
            if ($Daytype == 1) {
                $data['daytype'] = $Daytype;
                $hours = [];
                for ($i = 0; $i < 24; $i++) {
                    array_push($hours, $i);
                }
                foreach ($hours as $hour) {
                    $res = array_column(objToArray($HourRoomBill), null, 'time');
                    $data['HourRoomBill']['time'] = "$hour";
                    $data['HourRoomBill']['total'] = empty($res[$hour]['total']) ? "0" : $res[$hour]['total'];

                    $data2[] = $data['HourRoomBill'];
                }
                $data['HourRoomBill'] = empty($data2) ? [] : $data2;
            } else {
                $now = time();
                $timeBase = '2024-05-01';
                //项目起始日期
                if (empty($startDay) || (!empty($startDay) && strtotime($startDay) < strtotime($timeBase))) {
                    $starttime = $timeBase;
                }
                if (empty($endDay) || (!empty($endDay) && strtotime($endDay) > $now)) {
                    $endtime = date("Y-m-d", $now);
                }
                $starttime = strtotime($startDay);
                $endtime = strtotime($endDay);
                if ($Daytype == 3) {
                    $starttime = strtotime(date('Y-m-01', $starttime));
                } else {
                    $starttime = strtotime(date('Y-m-d', $starttime));
                }
                while ($starttime <= $endtime) {
                    $list[] = date('m-d', $starttime);
                    $starttime = $starttime + 86400;
                }
                foreach ($list as $date) {
                    $res = array_column(objToArray($dayRoomBill), null, 'time');
                    $data['HourRoomBill']['time'] = $date;
                    $data['HourRoomBill']['total'] = empty($res[$date]['total']) ? "0" : $res[$date]['total'];
                    $data2[] = $data['HourRoomBill'];
                }
                $data['HourRoomBill'] = empty($data2) ? [] : $data2;

            }
            $data['show_name'] = empty($room_id) ? '公会总流水（钻石）' : $room_info['name'] . ' 总流水（钻石）';
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    public function showUnionConsumerLogByReceiveUser($user_id, $room_id, $startDay, $endDay, $search_user_id, $page, $limit)
    {
        //获取用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 8, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '查看失败';
        $startTime = strtotime($startDay);
        $endTime = strtotime($endDay);
        $permisson = true;
        if (!empty($room_id)) {
            $permisson = $this->showRoomFinanceStream($user_id, $room_id);
        }
        do {
            if (!$union_info) {
                break;
            }
            if ($endTime - $startTime > 5184000) {
                $msg = '请查询60天内数据';
                break;
            }
            if ($check_role == 0 && !$permisson) {
                $msg = '无权操作';
                break;
            }
            //查看公会房间id
            if ($room_id) {
                $room_info = $this->model_room->get_room($room_id);
                if (empty($room_info)) {
                    $msg = '房间不存在';
                    break;
                }
            }
            //房间消费流水
            $res = $this->FinanceRoomWealth->getRoomConsumerUserLogBySendUser($union_id, $room_id, $startDay, $endDay, $page, $limit);

            //读取房间总数
            $total_diamond = $this->FinanceRoomWealth->getRoomConsumerTotalValue($union_id, $room_id, $startDay, $endDay);

            if (count($res) > 0) {
                //读取用户信息
                $userIds = array_merge(array_unique(array_column($res, 'user_id')));
                $v_user_info = $this->user->get_users_by_ids($userIds);
                $usersMap = array_column($v_user_info, null, 'user_id');

                //读取房间信息
                $roomIds = array_merge(array_unique(array_column($res, 'room_id')));
                $v_room_info = $this->model_room->get_rooms_by_ids($roomIds);
                $roomsMap = array_column($v_room_info, null, 'room_id');

                foreach ($res as &$v) {
                    $v['nickname'] = $usersMap[$v['user_id']]['nickname'] ?? '';
                    $v['user_uid'] = $usersMap[$v['user_id']]['user_uid'] ?? '';
                    $v['image'] = build_image($usersMap[$v['user_id']]['images'][0] ?? '');
                    $v['name'] = $roomsMap[$v['room_id']]['name'] ?? '';
                    $v['room_uid'] = $roomsMap[$v['room_id']]['room_uid'] ?? '';
                    $v['diamond_value'] = abs($v['diamond_value']);
                    $v['year'] = substr(date('Y-m-d', $v['create_timestamp']), 0, 4);
                    $v['month'] = substr(date('Y-m-d', $v['create_timestamp']), 5, 10);
                }
            }
            $data['total'] = $total_diamond;
            $data['list'] = $res;
            $data['show_name'] = empty($room_id) ? '公会总流水（钻石）' : $room_info['name'] . ' 总流水（钻石）';
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    public function showUnionConsumerUserList($user_id, $room_id, $startDay, $endDay, $search = '')
    {
        //获取用户公会信息
        $union_info = $this->model_user_union->userToUnion($user_id, 1);//操作用户公会信息
        $union_id = $union_info['un_id'];
        $check_role = $this->model_user_union->checkUserRole($user_id, 8, $union_id);//验证权限
        $code = Hint::ERR_FAIL;
        $msg = '查看失败';
        do {
            if (!$union_info) {
                break;
            }
            if ($check_role == 0) {
                $msg = '无权操作';
                break;
            }
            $room_ids[] = $room_id;
            //查看公会房间id
            if (!$room_id) {
                $union_rooms_ids = $this->model_union->getUnionRoomIds($union_id);
                if ($union_rooms_ids) {
                    $room_ids = array_column($union_rooms_ids, 'room_id');
                }
            }
            //房间消费人数
            $search_user_id = '';
            if ($search) {
                $search_user_info = $this->user->get_user_by_uid($search);
                $search_user_id = $search_user_info['user_id'];
            }
            $data = $this->FinanceRoomWealth->getRoomConsumerUserList($room_ids, $startDay, $endDay, $search_user_id);
            foreach ($data as &$v) {
                $v_user_info = $this->user->get_user($v['user_id'], false);
                $v['nickname'] = $v_user_info['nickname'];
                $v['user_uid'] = $v_user_info['user_uid'];
                $v['image'] = build_image($v_user_info['images'][0]);
            }
            $code = Hint::SUCCESS;
            $msg = '成功';
            break;
        } while (false);
        return compact('code', 'msg', 'data');
    }

    public function cmsKickUnionUser()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('user_id', '用户id', 'int', true);
            $this->I('union_id', '公会id', 'int', true);
            $variables = [];

            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $params = $this->requestData;
            $user_id = $params['user_id'];
            $union_id = $params['union_id'];
            $res = $this->model_user_union->quitUserUnion($union_id, $user_id);
            if (!$res) {
                $code = Hint::ERROR;
                $msg = '踢出失败';
                break;
            }
            //删除用户代理
            $this->userAgentModel->agentUserDel($user_id);
            //删除公会成员马甲
            $union_info = $this->model_user_union->userToUnion($union_id, 3);
            if (!empty($union_info['vest'])) {
                $this->user->batchSetUnionVest(array($user_id), '', 0);
            }
        } while (false);
        return compact('code', 'msg', 'data');
    }

    //来来语音116号需求-公会体系迭代

    /**创建公会
     * @return array
     */
    public function appCreateUnion($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            //检验公会名称是否存在
            $unionName = trim($params['name']);
            if (empty($unionName)) {
                $code = Hint::PARAM_ERROR;
                $msg = '公会昵称不能为空';
                break;
            }
            $union = $this->model_union->checkUnionName($unionName);
            if (!empty($union)) {
                $code = Hint::ERR_DATA_EXIST;
                $msg = '公会昵称已存在';
                break;
            }
            $user = $this->user->get_current_user();
            //判断是否实名验证
            $user_verify = $this->model_user_verify->getSuccess($user['user_id']);
            if (empty($user_verify)) {
                $code = Hint::USER_NOT_CERTIFICATION;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            //判断同一个实名认证客户是否创建过公会
            $idCard_number = $user_verify['idcard_number'];
            $idCardCount = $this->model_user_verify->getAllIcCard($idCard_number);
            $user_ids = array_column($idCardCount, 'user_id');
            $union_info = $this->model_union->getUnionInfoToUnUserId($user_ids);
            if (!empty($union_info)) {
                $code = Hint::UNION_CERTIFICATION_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            //判断用户是否加入过公会
            $union_user = $this->model_union->getUserUnion([$user['user_id']]);
            if (!empty($union_user)) {
                $code = Hint::UNION_USER_EXIST;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $res['name'] = $unionName;
            $res['uuid'] = $user['user_uid'];
            $res['un_user_id'] = $user['user_id'];
            $res['portrait'] = '/icon/default_icon.png';
            $res['sort'] = 0;
            $res['notice'] = '';
            $res['desc'] = '';
            $union_id = $this->model_union->createUnion($res, false);
            if ($union_id == -1) {
                $code = Hint::UNION_CREATE_TIMES_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            } else if ($union_id == 0) {
                $code = Hint::ERR_FAIL;
                $msg = '创建公会' . Hint::getErrCodeMsg($code);
                break;
            }
            $union_data['un_id'] = $union_id;
            $union_data['user_id'] = $user['user_id'];
            $union_data['role_id'] = 1; // 会长权限id
            $this->model_user_union->createUnionUser($union_data);
            $data['union_id'] = $union_id;
            $data['portrait'] = '/album/default.png';
            $data['name'] = $unionName;
            $data['user_id'] = $user['user_id'];
            $this->model_union_rank->setContribution($union_id);

            $this->checkUserSetAgent($user['user_id']);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function noticeList()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('union_id', '公会id', 'int', true);
            $this->I('page', '页数', 'int', false);
            $this->I('pageSize', '数量', 'int', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $page = $this->requestData['page'] ?? 0;
            $pageSize = $this->requestData['pageSize'] ?? 10;
            $data = $this->model_union->getNoticeList($this->requestData['union_id'], $page, $pageSize);
            $user_ids = array_column($data, 'user_id');
            $users = $this->user->get_users_by_ids($user_ids);
            $id_name = array();
            foreach ($users as $u) {
                $id_name[$u['user_id']] = $u['nickname'];
            }
            foreach ($data as &$val) {
                $val['nickname'] = isset($id_name[$val['user_id']]) ? $id_name[$val['user_id']] : '';
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function addNotice()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('union_id', '公会id', 'int', true);
            $this->I('content', '内容', 'string', true);
            $this->I('user_id', '用户id', 'int', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            //校验用户是否有权限
            $user_identify = $this->model_user_union->userRole($this->requestData['user_id'], $this->requestData['union_id']);
            if (empty($user_identify) || $user_identify['role_id'] == 0) {
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $res['union_id'] = $this->requestData['union_id'];
            $res['user_id'] = $this->requestData['user_id'];
            $res['content'] = $this->requestData['content'];
            $data = $this->model_union->addNotice($res);
            $this->model_content_check->create($this->requestData['user_id'], 16, $this->requestData['content'], '', $this->requestData['union_id'], '', $data);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function delNotice()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('id', '公告id', 'int', true);
            $this->I('union_id', '公会id', 'int', true);
            $this->I('user_id', '用户id', 'int', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            //校验用户是否有权限
            $user_identify = $this->model_user_union->userRole($this->requestData['user_id'], $this->requestData['union_id']);
            if (empty($user_identify) || $user_identify['role_id'] == 0) {
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $data = $this->model_union->delNotice($this->requestData['id']);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function setUnionInfo()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('union_id', 'union_id', 'int', true);
            $this->I('user_id', 'user_id', 'int', true);
            $this->I('portrait', '公会头像', 'string', false);
            $this->I('name', '公会名称', 'string', false);
            $this->I('declaration', '公会宣言', 'string', false);
            $this->I('vest', '公会马甲', 'string', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
//            if(empty($this->requestData['name']) && empty($this->requestData['portrait'])
//                && empty($this->requestData['declaration']) && empty($this->requestData['vest'])){
//                $code = Hint::PARAM_ERROR;
//                $msg = Hint::getErrCodeMsg($code);
//                break;
//            }
            //校验用户是否有权限
            $user_identify = $this->model_user_union->userRole($this->requestData['user_id'], $this->requestData['union_id']);
            if (empty($user_identify) || !in_array($user_identify['role_id'], [1, 2])) {
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $union = $this->model_union->getUnionInfo($this->requestData['union_id']);
            if (empty($union)) {
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            //24小时只允许修改一次公会名称
            $update_time = $this->model_union->getUpdateNameTime($this->requestData['union_id']);
            if (!empty($this->requestData['name']) && !empty($update_time)) {
                $code = Hint::UNION_UPDATE_NAME_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            //24小时只允许修改一次公会马甲
            $vest_update_time = $this->model_union->getVestTime($this->requestData['union_id']);
            if (isset($this->requestData['vest']) && !empty($vest_update_time)) {
                $code = Hint::UNION_UPDATE_NAME_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            //公会不能不能重
            if (!empty($this->requestData['name'])) {
                $this->requestData['name'] = trim($this->requestData['name']);
                $checkUnionName = $this->model_union->checkUnionName($this->requestData['name']);
                if (!empty($checkUnionName)) {
                    $code = Hint::ERR_DATA_EXIST;
                    $msg = '公会昵称已存在';
                    break;
                }
            }
            if (empty($this->requestData['vest'])) {
                $data = $this->model_union->setUnionInfo($this->requestData);
            }
            if (isset($this->requestData['vest']) && empty($this->requestData['vest'])) {
                $this->model_union->setVestTime($union['id']);
                DB::beginTransaction();
                $users = $this->model_user_union->getUserNum($this->requestData['union_id'], false);
                $user_ids = array_column($users, 'user_id');
                $this->user->batchSetUnionVest($user_ids, '', 0);
                DB::commit();
            }
            if (!empty($this->requestData['name'])) {
                $this->model_content_check->create($this->requestData['user_id'], 14, $this->requestData['name'], $union['name'], $union['id']);
            } else if (!empty($this->requestData['declaration'])) {
                $this->model_content_check->create($this->requestData['user_id'], 15, $this->requestData['declaration'], $union['declaration'], $union['id']);
            } else if (!empty($this->requestData['vest'])) {
                $this->model_union->setVestTime($union['id']);
                $this->model_content_check->create($this->requestData['user_id'], 17, $this->requestData['vest'], $union['vest'], $union['id']);
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function checkPresidentStatus()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('union_id', '公会id', 'int', true);
            $this->I('user_id', '用户id', 'int', true);
            $this->I('sms_token', 'token', 'string', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $union = $this->model_union->getUnionInfo($this->requestData['union_id']);
            if (empty($union)) {
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            if ($union['un_user_id'] != $this->requestData['user_id']) {
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $union_num = $this->model_user_union->getUserNum($this->requestData['union_id']);
            if ($union_num >= 50) {
                $code = Hint::ERR_FAIL;
                $msg = '公会人数少于50时才可以解散';
                break;
            }
            $user = $this->user->get_current_user();
            if (!empty($user['phone'])) {
                $phone = $user['phone'];

                $alicodeConfig = $this->systemServices->getAliVerify();
                if ($alicodeConfig['status'] == 1) {
                    if (empty($this->requestData['sms_token'])) {
                        $code = Hint::ERR_FAIL;
                        $msg = '系统检测您的版本过低,请升级最新版本';
                        break;
                    }
                    $cacheSms = Redis::get('ALI:VERIFY:TOKEN:' . $phone);
                    if (($cacheSms != md5($phone)) || empty($cacheSms)) {
                        $code = Hint::ERR_FAIL;
                        $msg = '验证失效';
                        break;
                    }
                }

                $smsCode = randomkeys();
                $expireTime = 5 * 60;
                $smsObj = new SendSms();
                $result = $smsObj->spSendSingleSms($user['phone'], $smsCode);
                if ($result) {
                    //redis 存储
                    $redisKey = 'sms_union_' . $user['phone'];
                    $this->model_union->redisCache($redisKey, $smsCode, $expireTime);
                } else {
                    $code = Hint::ERR_FAIL;
                    $msg = '短信验证码发送失败';
                    break;
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function checkPresidentCode()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('union_id', '公会id', 'int', true);
            $this->I('user_id', '用户id', 'int', true);
            $this->I('sms_code', '验证码', 'string', true);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $user = $this->user->get_current_user();
            if (empty($user['phone'])) {
                $code = Hint::ERR_FAIL;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $union = $this->model_union->getUnionInfo($this->requestData['union_id']);
            if ($union['un_user_id'] != $this->requestData['user_id']) {
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            //校验验证码
            $sms_cache_code = $this->model_union->redisCacheGet('sms_union_' . $user['phone']);
            if ($sms_cache_code != $this->requestData['sms_code']) {
                $code = Hint::SMS_CODE_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $data = $this->model_union->generateDissolveCode($this->requestData['union_id']);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function appDissolveUnion()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('union_id', 'union_id', 'int', true);
            $this->I('user_id', 'user_id', 'int', true);
            $this->I('dissolve_code', 'dissolve_code', 'string', true);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $user = $this->user->get_current_user();
            if (empty($user['phone'])) {
                $code = Hint::ERR_FAIL;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            //校验解散公会的解散码
            $dissolve_cache_code = $this->model_union->getDissolveCode($this->requestData['union_id']);
            if (empty($dissolve_cache_code) || ($dissolve_cache_code != $this->requestData['dissolve_code'])) {
                $code = Hint::UNION_DISSOLVE_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $user_id = $this->requestData['user_id'];
            $union_info = $this->model_user_union->userToUnion($user_id, 3);
            $data['union_id'] = $union_info['un_id'];


            if ($union_info['un_user_id'] == $user_id && $union_info['role_id'] == 1) {
                DB::beginTransaction();
                try {
                    //删除公会信息
                    $this->model_union->delUnion($union_info['un_id'], $user_id);
                    $this->model_union->delUnionRoom($union_info['un_id']);
                    //公会用户
                    $users = $this->model_user_union->getUserNum($this->requestData['union_id'], false);
                    $user_ids = array_column($users, 'user_id');

                    //删除公会成员的马甲
                    if (!empty($union_info['vest'])) {
                        $this->user->batchSetUnionVest($user_ids, '', 0);
                    }

                    //解散公会成员
                    $res = $this->model_user_union->quitUserUnion($union_info['union_id']);
                    if (!$res) {
                        $code = Hint::ERR_FAIL;
                        $msg = '解散公会失败';
                        DB::rollBack();
                        break;
                    }

                    //删除用户代理
                    $this->userAgentModel->agentUserDelList($user_ids);

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    $code = Hint::ERROR;
                    $msg = '更新系统异常';
                    break;
                }

                $this->model_union_rank->delContribution($this->requestData['union_id']);
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function getRoomUserList()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('union_id', '公会id', 'int', true);
            $this->I('user_id', '用户id', 'int', true);
            $this->I('room_id', '房间id', 'int', true);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $union_users = $this->model_user_union->getUserNum($this->requestData['union_id'], false);
            $union_roles = $this->model_user_union->getRolesList();
            $room_admin = $this->model_room->get_roles_all_by_role_type($this->requestData['room_id'], 2);
            $room_admin = array_column($room_admin, 'create_timestamp', 'user_id');
            $admin_arr = [];
            $member_arr = [];
            foreach ($union_users as &$union_user) {
                if (isset($union_roles[$union_user['role_id']])) {
                    $union_user['role_name'] = $union_roles[$union_user['role_id']];
                }
                $user = $this->user->get_user($union_user['user_id']);
                if (!empty($user)) {
                    $union_user['portrait'] = $user['images'][0];
                    $union_user['nickname'] = $user['nickname'];
                    $union_user['user_uid'] = $user['user_uid'];
                }
                $union_user['role_temp_id'] = $union_user['role_id'] == 0 ? 10 : $union_user['role_id'];
                if (isset($room_admin[$union_user['user_id']])) {
                    $union_user['is_admin'] = 1;
                    $union_user['admin_time'] = $room_admin[$union_user['user_id']];
                    $admin_arr[] = $union_user;
                } else {
                    $union_user['is_admin'] = 0;
                    $union_user['admin_time'] = 0;
                    $member_arr[] = $union_user;
                }
            }
            $role_sort = array_column($admin_arr, 'role_temp_id');
            $admin_time = array_column($admin_arr, 'admin_time');

            array_multisort($role_sort, SORT_ASC, $admin_time, SORT_DESC, $admin_arr);


            $created_at = array_column($member_arr, 'created_at');
            array_multisort($created_at, SORT_DESC, $member_arr);

            $data['admin'] = $admin_arr;
            $data['member'] = $member_arr;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //获取公会财富等级与活跃等级
    public function getGrade($data)
    {
        return $this->model_union->getGrade($data['id']);
    }

    public function inviteJoin()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('invite_user_id', '用户', 'int', true);
            $this->I('union_id', '公会id', 'int', true);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $user_info = $this->user->get_current_user();
            $union_info = $this->model_union->getUnionInfo($this->requestData['union_id']);
            if (empty($union_info)) {
                $code = Hint::ERROR;
                $msg = '公会已解散！';
                break;
            }
            if ($user_info['user_id'] != $union_info['un_user_id']) {
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $this->model_union->setUnionInvite($this->requestData['union_id'], $this->requestData['invite_user_id']);
            $data['id'] = $union_info['id'];
            $data['name'] = $union_info['name'];
            $data['image'] = build_image($union_info['portrait']);
            $data['un_user_id'] = $union_info['un_user_id'];
            $data['un_user_name'] = $user_info['nickname'];
            $data['invite_user_id'] = $this->requestData['invite_user_id'];
        } while (false);

        return compact('code', 'msg', 'data');

    }

    //通过
    public function searchUserByUuid($unionId, $uuid)
    {
        $user = (new User())->getUserByUuid($uuid);
        if (empty($user)) {
            return null;
        }
        $isUnionUser = $this->model_user_union->isUnionUser($unionId, $user['user_id']);
        if (!$isUnionUser) {
            return null;
        }
        return $user;
    }

    //通过
    public function getUnionRoleById($unionId, $userId)
    {
        return $this->model_user_union->getUnionRoleById($unionId, $userId);
    }

    //获取公会对公结算数据
    public function getUnionSettleInfo($userId, $unionId, $dateSt, $dateEd)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //没选择结算周期就是上一周
            if (empty($dateSt) || empty($dateEd)) {
                $time = strtotime("-7 days");
                $num = date("N", $time);
                $dateSt = strtotime(date("Y-m-d 00:00:00", $time - 86400 * ($num - 1)));
                $dateEd = strtotime(date("Y-m-d 00:00:00", ($dateSt + 86400 * 6)));
            }

            //必须是公会长
            $unionInfo = $this->model_union->getUnionInfo($unionId);
            if (empty($unionInfo) || $unionInfo['un_user_id'] != $userId) {
                $code = Hint::AUTH_ERROR;
                break;
            }
            //结算类型
            if ($unionInfo['settle_type'] != 2) {
                $code = Hint::AUTH_ERROR;
                $msg = '不是对公结算公会';
                break;
            }

            //数据获取
            $settleInfo = $this->settleModel->getUnionSettleByUnionIdDate($unionId, $dateSt, $dateEd);
            if (empty($settleInfo)) {
                $settleInfo = [];
                $settleInfo['id'] = 0;
                $settleInfo['union_id'] = $unionId;
                $settleInfo['user_id'] = $userId;
                $settleInfo['settle_date_st'] = $dateSt;
                $settleInfo['settle_date_ed'] = $dateEd;
                $settleInfo['settle_kk'] = 0;
                $settleInfo['status'] = 0;
            } else {
                $settleInfo['settle_docx'] = build_url($settleInfo['settle_docx']);
                $settleInfo['confirm_img'] = build_url($settleInfo['confirm_img']);
                $settleInfo['invoice_img'] = build_url($settleInfo['invoice_img']);
            }

            $data = $settleInfo;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //公会对公结算提交
    public function submitUnionSettle($userId, $unionId, $id, $confirmImg, $invoiceImg)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //获取记录
            $logInfo = $this->settleModel->getUnionSettleById($id);
            if (empty($id) || empty($logInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            if ($logInfo['union_id'] != $unionId) {
                $code = Hint::PARAM_ERROR;
                $msg = '传入参数数据异常';
                break;
            }
            if (!in_array($logInfo['status'], [1, 4])) {
                $code = Hint::PARAM_ERROR;
                $msg = '当前结算状态不可编辑';
                break;
            }

            //必须是公会长
            $unionInfo = $this->model_union->getUnionInfo($unionId);
            if (empty($unionInfo) || $unionInfo['un_user_id'] != $userId) {
                $code = Hint::AUTH_ERROR;
                break;
            }
            //结算类型
            if ($unionInfo['settle_type'] != 2) {
                $code = Hint::AUTH_ERROR;
                $msg = '不是对公结算公会';
                break;
            }

            //更新
            $this->settleModel->updateUnionSettle($logInfo['id'], ['status' => 2, 'confirm_img' => $confirmImg, 'invoice_img' => $invoiceImg]);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 设置公会奖励类型
     */
    public function unionSetRewardType($unionId, $rewardType)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($unionId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $info = $this->model_union->getUnionByUnionId($unionId);
            if (empty($info)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            if ($info['reward_type'] == $rewardType) {
                $code = Hint::PARAM_ERROR;
                $msg = '当前已是指定公会奖励类型,请勿重复设置';
                break;
            }

            $this->model_union->updateUnion($unionId, ['reward_type' => $rewardType]);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 判断用户是否是主播是主播的话设置为代理
     */
    public function checkUserSetAgent($userId)
    {
        // 甜枕去除此逻辑
        return false;

        //用户身份
        $unionInfo = $this->model_union->getUserUnionInfo($userId);
        if (empty($unionInfo)) {
            return false;
        }
        //查询用户当前代理状态
        $info = $this->userAgentModel->getUserAgent($userId);
        if (!empty($info)) {
            if ($info['status'] == 1) {
                return true;
            }
        }
        //暂停代理操作
        $cacheKey = 'USER:AGENT:' . $userId;
        if (!redis_lock($cacheKey, 10)) {
            return false;
        }
        try {
            $this->userAgentModel->agentUserAdd($userId, 0);
        } catch (\Exception $e) {

        }
        redis_unlock($cacheKey);
    }

    /**
     * 公会主播私信统计列表
     */
    public function getIdentityMsgStatList($page, $limit, $userId, $timeSt, $timeEd)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = ['list' => []];

        do {
            //发信用户公会
            $unionInfo = $this->model_union->getUserUnionInfo($userId);
            if (empty($unionInfo)) {
                $code = Hint::AUTH_ERROR;
                break;
            }
            //必须是会长
            $showUserId = 0;
            if ($userId != $unionInfo['un_user_id']) {
                $showUserId = $userId;
            }
            $unionId = $unionInfo['id'];
            $timeSt = empty($timeSt) ? 0 : date('Ymd', $timeSt);
            $timeEd = empty($timeEd) ? 0 : date('Ymd', $timeEd);

            $list = $this->user->unionUserMsgStatList($page, $limit, $unionId, $timeSt, $timeEd, $showUserId);
            if (!empty($list)) {
                $userIds = array_column($list, 'from_user_id');
                $usersMap = $this->user->get_users_by_ids($userIds);
                $usersMap = array_column($usersMap, null, 'user_id');

                foreach ($list as $val) {
                    $val['uuid'] = empty($usersMap[$val['from_user_id']]['user_uid']) ? '' : $usersMap[$val['from_user_id']]['user_uid'];
                    $val['nickname'] = empty($usersMap[$val['from_user_id']]['nickname']) ? '' : $usersMap[$val['from_user_id']]['nickname'];
                    $val['image'] = build_image(empty($usersMap[$val['from_user_id']]['images'][0]) ? '' : $usersMap[$val['from_user_id']]['images'][0]);

                    $data['list'][] = $val;
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 公会指定主播私信统计
     */
    public function getIdentityMsgStat($userId, $timeSt, $timeEd)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            //发信用户公会
            $unionInfo = $this->model_union->getUserUnionInfo($userId);
            if (empty($unionInfo)) {
                $code = Hint::AUTH_ERROR;
                break;
            }
            $unionId = $unionInfo['id'];
            $timeSt = empty($timeSt) ? 0 : date('Ymd', $timeSt);
            $timeEd = empty($timeEd) ? 0 : date('Ymd', $timeEd);

            $list = $this->user->unionUserMsgStatList(1, 1, $unionId, $timeSt, $timeEd, $userId);
            if (!empty($list)) {
                $userIds = array_column($list, 'from_user_id');
                $usersMap = $this->user->get_users_by_ids($userIds);
                $usersMap = array_column($usersMap, null, 'user_id');

                foreach ($list as $val) {
                    $val['uuid'] = empty($usersMap[$val['from_user_id']]['user_uid']) ? '' : $usersMap[$val['from_user_id']]['user_uid'];
                    $val['nickname'] = empty($usersMap[$val['from_user_id']]['nickname']) ? '' : $usersMap[$val['from_user_id']]['nickname'];
                    $val['image'] = build_image(empty($usersMap[$val['from_user_id']]['images'][0]) ? '' : $usersMap[$val['from_user_id']]['images'][0]);

                    $data['list'][] = $val;
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 公会主播私信统计列表导出申请
     */
    public function addIdentityMsgStatExcel($userId, $timeSt, $timeEd)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            //发信用户公会
            $unionInfo = $this->model_union->getUserUnionInfo($userId);
            if (empty($unionInfo)) {
                $code = Hint::AUTH_ERROR;
                break;
            }
            //必须是会长
            if ($userId != $unionInfo['un_user_id']) {
                $code = Hint::AUTH_ERROR;
                break;
            }
            $unionId = $unionInfo['id'];
            $timeSt = empty($timeSt) ? 0 : date('Ymd', $timeSt);
            $timeEd = empty($timeEd) ? 0 : date('Ymd', $timeEd);

            $param = [
                'userId' => $userId,
                'unionId' => $unionId,
                'timeSt' => $timeSt,
                'timeEd' => $timeEd,
            ];
            $param = [
                'user_id' => $userId,
                'exec_url' => '',
                'condition' => json_encode([
                    'unionId' => $unionId,
                    'timeSt' => $timeSt,
                    'timeEd' => $timeEd,
                ]),
                'type' => 1,
                'status' => 0,
            ];
            $id = $this->user->createUserExcelLog($param);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 公会主播私信统计导出列表
     */
    public function getIdentityMsgStatExcelList($page, $limit, $userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = ['list' => []];

        do {
            //发信用户公会
            $unionInfo = $this->model_union->getUserUnionInfo($userId);
            if (empty($unionInfo)) {
                $code = Hint::AUTH_ERROR;
                break;
            }
            //必须是会长
            if ($userId != $unionInfo['un_user_id']) {
                $code = Hint::AUTH_ERROR;
                break;
            }

            $list = $this->user->getUserExcelLogList($page, $limit, $userId, 1);
            if (!empty($list)) {
                foreach ($list as $val) {
                    if ($val['status'] == 1) {
                        $val['exec_url'] = build_url($val['exec_url']);
                    }
                    $val['condition'] = json_decode($val['condition'], true);
                    $val['timeEd'] = empty($val['condition']['timeEd']) ? '无' : date("Y年m月d日", strtotime($val['condition']['timeEd']));
                    $val['timeSt'] = empty($val['condition']['timeSt']) ? '无' : date("Y年m月d日", strtotime($val['condition']['timeSt']));

                    $data['list'][] = $val;
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }


}
